我有以下视图规范:
describe "carts/show" do
before(:each) do
book = build_stubbed(:product, title: "book")
car = build_stubbed(:product, title: "car")
line_item1 = build_stubbed(:line_item, product: book, quantity: 3)
line_item2 = build_stubbed(:line_item, product: car, quantity: 1)
@cart = assign(:cart, build_stubbed(:cart, line_items: [line_item1, line_item2]))
render
end
it "displays a single car" do
assert_select "li", text: "1 time: car"
end
it "displays 3 books" do
assert_select "li", text: "3 times: book"
end
it "has exactly 2 items" do
assert_select "li", 2
end
end
此规范按预期工作。但是,因为设置在一个before(:each)
块中,所以设置和render
方法在每个块中调用一次。这很慢。理想情况下,它们应该只为整个describe
块调用一次。
我想before(:each)
改成before(:all)
可以解决这个问题,但我得到了错误(show.html.erb_spec.rb 中的第 16 行是render
调用):
NoMethodError: undefined method `example_group' for nil:NilClass
~/.rvm/gems/ruby-1.9.3-p125/gems/rspec-rails-2.12.0/lib/rspec/rails/example/view_example_group.rb:106:in `_default_file_to_render'
~/.rvm/gems/ruby-1.9.3-p125/gems/rspec-rails-2.12.0/lib/rspec/rails/example/view_example_group.rb:112:in `_default_render_options'
~/.rvm/gems/ruby-1.9.3-p125/gems/rspec-rails-2.12.0/lib/rspec/rails/example/view_example_group.rb:45:in `render'
show.html.erb_spec.rb:16:in `block (2 levels) in <top (required)>'
~/.rvm/gems/ruby-1.9.3-p125/gems/rspec-core-2.12.1/lib/rspec/core/hooks.rb:23:in `instance_eval'
~/.rvm/gems/ruby-1.9.3-p125/gems/rspec-core-2.12.1/lib/rspec/core/hooks.rb:23:in `run'
~/.rvm/gems/ruby-1.9.3-p125/gems/rspec-core-2.12.1/lib/rspec/core/hooks.rb:106:in `run'
~/.rvm/gems/ruby-1.9.3-p125/gems/rspec-core-2.12.1/lib/rspec/core/hooks.rb:424:in `run_hook'
~/.rvm/gems/ruby-1.9.3-p125/gems/rspec-core-2.12.1/lib/rspec/core/example_group.rb:319:in `run_before_all_hooks'
~/.rvm/gems/ruby-1.9.3-p125/gems/rspec-core-2.12.1/lib/rspec/core/example_group.rb:368:in `run'
~/.rvm/gems/ruby-1.9.3-p125/gems/rspec-core-2.12.1/lib/rspec/core/command_line.rb:28:in `block (2 levels) in run'
~/.rvm/gems/ruby-1.9.3-p125/gems/rspec-core-2.12.1/lib/rspec/core/command_line.rb:28:in `map'
~/.rvm/gems/ruby-1.9.3-p125/gems/rspec-core-2.12.1/lib/rspec/core/command_line.rb:28:in `block in run'
~/.rvm/gems/ruby-1.9.3-p125/gems/rspec-core-2.12.1/lib/rspec/core/reporter.rb:34:in `report'
~/.rvm/gems/ruby-1.9.3-p125/gems/rspec-core-2.12.1/lib/rspec/core/command_line.rb:25:in `run'
~/.rvm/gems/ruby-1.9.3-p125/gems/rspec-core-2.12.1/lib/rspec/core/runner.rb:80:in `run'
~/.rvm/gems/ruby-1.9.3-p125/gems/rspec-core-2.12.1/lib/rspec/core/runner.rb:17:in `block in autorun'
我不知道我还能在这里做什么。解决这个问题的正确方法是什么?