2013-05-08 37 views
3

使用Railscast示例,我爲我的演示者編寫了一個規範,其中包括ActionView::TestCase::Behavior並將view方法傳遞給演示者。使用ActionView :: TestCase :: Behavior和演示者中的視圖方法規範

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認爲做這魔法)。

回答

4

我現在的解決方案是通過在演示者規範之前調用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 
+0

你是我的英雄,沒有別的任何地方,這個問題有所幫助。你找到根源了嗎? – Goodwine 2015-03-18 19:21:19

相關問題