是否正确使用assert_select进行RSpec控制器测试?

时间:2012-03-08 15:35:31

标签: ruby-on-rails rspec rspec-rails

我一直无法找到关于编写好的RSpec控制器测试的文档或建议。具体来说,你应该使用感觉与RSpec非常不同的Rails'assert_select还是有替代品呢?

以下示例是最佳做法吗?

describe ArticlesController do
  render_views
  let(:article) { create(:article) }

  describe "show" do
    it "should display the article title" do
      get :show, id: article
      response.should be_success
      assert_select "h1", article.title
    end
  end
end

我不想写单独的视图测试,因为这非常不方便。

1 个答案:

答案 0 :(得分:0)

您应该能够使用以下代码检查标题内容:

page.should have_selector("h1", :text => article.title)

更新:有人注意到(带-1)答案错误,page变量是Capybara在调用visit方法后设置的内容(当我回答时,我还年轻:P)。所以这是你在集成测试中使用的东西,而不是你正在尝试的功能测试(控制器)。

简短回答:不,在控制器测试中使用assert_select是不正确的(用于检查请求响应,如果设置了变量等等)

相关问题