测试视图已使用spec呈现

时间:2013-12-08 18:35:32

标签: ruby-on-rails rspec

首先render_template方法背后的意义是什么?什么是模板?这是一个观点吗?在这种情况下,在控制器规范中,

response.should render_template('show')

对此控制器的请求是否应该呈现名为show.html.erb的视图?或者控制器应包含此

render 'show'

所以,如果我正确地想到这一点,那么测试该视图的最佳方法是什么?

选项1:

it "should render a view" do
    response.should contain("I am the show view") # assuming the text is present in the view
end

选项2:

it "should render a view" do
    response.should render_template('show')
end 

选项2 只有在控制器中明确拥有render 'show'时才会通过吗?

def create
    if params[:friend_id]

        @friend = User.find_by_profile_name(params[:friend_id])




    else

    end

    if @friend.profile_name != nil

        @user_friendship = current_user.user_friendships.new(friend: @friend)
        @user_friendship.save
        redirect_to profile_path(@friend.profile_name), status: 302

    else
        flash[:error] = "Friend required!"
        redirect_to root_path, status: 302
    end 
end

使用有效请求测试create操作时,profile_path确实会导致显示视图,但这是否超出了规范的范围?我看到你收到这个错误:

 Failure/Error: response.should render_template('show')
   expecting <"show"> but rendering with <[]>

还是另一种方式?

此外,为了在rspec测试中使用contain等方法,需要安装无头服务器(如capybara-webkit)或头部服务器(例如selinium-webdriver) ?

1 个答案:

答案 0 :(得分:1)

您不应该在一次测试中测试它。你会发现自己正在修复&#39;当您决定更改应用程序的流程时,测试整个地方。

使用单独的测试:

  • 测试创建请求被重定向到profile_path
  • 测试profile_path是否呈现&#34;显示&#34;

示例:

describe "POST #create" do
  it "should redirect to profile_path" do
    post 'create', valid_params
    response.should redirect_to profile_path
  end
end

describe "GET #show" do
  it "should render show template" do
    get 'show', valid_params 
    response.should render_template('show')
  end
end
相关问题