在视图中的存根模型

时间:2013-12-15 14:33:14

标签: ruby-on-rails testing view rspec specifications

我不想用Rspec在Rails中编写视图的规范。我写了这个:

require 'spec_helper'

describe "homepage/index.html.erb" do
  it 'has list of publications with id #publications' do
    render
    expect(rendered).to have_selector('ul#publications')
  end

  it 'has publications on the list' do
    assign(:publications, [
      stub_model(Publication, content: 'First publication.'),
      stub_model(Publication, content: 'Second publication.')
    ])
    render
    rendered.should have_content('First publication.')
    rendered.should have_content('Second publication.')
  end
end

但是stub_model似乎没有用。

rspec
.....F.

Failures:

  1) homepage/index.html.erb has list of publications with id #publications
     Failure/Error: render
     ActionView::Template::Error:
       undefined method `each' for nil:NilClass
     # ./app/views/homepage/index.html.erb:2:in `_app_views_homepage_index_html_erb___3273264012123365698_43368240'
     # ./spec/views/homepage/index.html.erb_spec.rb:5:in `block (2 levels) in <top (required)>'

Finished in 0.17634 seconds
7 examples, 1 failure

如何正确存根?

2 个答案:

答案 0 :(得分:1)

您的失败消息中给出的描述表明您的示例上面的失败带有存根的示例。在该示例中,没有为实例变量@publications分配任何内容,因此视图可能会引发您在执行@publications.each ...时看到的错误。

但正如@phoet暗示的那样,你真的应该提供失败的代码。

答案 1 :(得分:0)

我不认为在这种(集成或验收)测试中存根模型是个好主意。

但是如果你想这样做,你应该将查询存根到DB(当你尝试存根分配时)。例如,你的行动中有Publication.all - 所以你可以存根

Publication.stub(all:
  [
    stub_model(Publication, content: 'First publication.'),
    stub_model(Publication, content: 'Second publication.')
  ])