使用 Railscast 示例,我为演示者编写了规范,其中包括 ActionView::TestCase::Behavior
并将 view
方法传递给演示者。
spec/spec_helper.rb
:
...
config.include ActionView::TestCase::Behavior, :example_group => {:file_path => %r{spec/presenters}}
...
spec/presenters/order_presenter_spec.rb
:
require 'spec_helper'
describe OrderPresenter do
describe "#subtotal" do
subject { OrderPresenter.new(order, view).subtotal }
let(:order) { stub(:order, working_subtotal: 4500) }
it "renders the subtotal table row" do
should == "<tr><th>SUBTOTAL</th><td>$45.00</td></tr>"
end
end
end
但是,这给了我两个错误。 第一个是
/Users/shevaun/.rvm/gems/ruby-1.9.3-p392/gems/actionpack-3.2.13/lib/action_controller/test_case.rb:12:in `block in <module:TemplateAssertions>': undefined method `setup' for #<Class:0x007fe2343b2f40> (NoMethodError)
所以我以与 ActionView::TestCase::Behavior
相同的方式包含了 ActiveSupport::Testing::SetupAndTeardown
。
修复错误:
NoMethodError:
undefined method `view_context' for nil:NilClass
当调用 view
时。这是由 ActionView::TestCase
中的 @controller
实例变量 nil
引起的。
我正在使用 Rails 3.2.13 和 rspec-rails 2.13.0,并且有另一个使用相同版本的应用程序,可以正常工作。
我能想到的唯一可能有所不同的是这个应用程序正在使用 MongoDB,所以也许 ActiveRecord 应用程序包含一些可以免费设置 @controller
的东西?
我有一个解决方法可以使演示者规范通过,但我想知道 @controller
通常是如何实例化的,以及是否有更优雅的方法来为 MongoDB 项目执行此操作(如果是 ActiveRecord 发挥了魔力)。
最佳答案
我目前的解决方案是通过在演示者规范之前调用 setup_with_controller
来实例化 @controller
实例变量。
spec_helper.rb
:
RSpec.configure do |config|
config.include ActiveSupport::Testing::SetupAndTeardown, :example_group => {:file_path => %r{spec/presenters}}
config.include ActionView::TestCase::Behavior, :example_group => {:file_path => %r{spec/presenters}}
config.before(:each, example_group: {:file_path => %r{spec/presenters}}) do
setup_with_controller # this is necessary because otherwise @controller is nil, but why?
end
...
end
关于ruby-on-rails - 在 Presenter 规范中使用 ActionView::TestCase::Behavior 和 View 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16430581/