【问题标题】:Stub model in a view视图中的存根模型
【发布时间】:2013-12-15 14:33:14
【问题描述】:

我不想用 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

我怎样才能正确地存根?

【问题讨论】:

  • 我对你的问题投了反对票,因为你没有提供index.html.erb的相关代码。
  • 我认为这很明显......但无论如何我问得太快了。失败的测试是第一个,而不是第二个。所以我将分配转移到before 并且效果很好。

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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2018-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-18
      • 1970-01-01
      相关资源
      最近更新 更多