2008-12-22 48 views
3

我有一些視圖規格需要某些方法被殘留。這是我想會的工作(在spec_helper.rb):什麼是使用rspec-rails在所有視圖規範上存根模板方法的正確方法?

Spec::Runner.configure do |config| 
    config.before(:each, :type => :views) do 
     template.stub!(:request_forgery_protection_token) 
     template.stub!(:form_authenticity_token) 
    end 
end 

但是當我運行任何視圖規範它失敗

You have a nil object when you didn't expect it! The error occurred while evaluating nil.template

做在之前完全一樣的東西( :每個)每個示例的塊都很好。

回答

3

我嘗試了你的例子,發現在「config.before」塊的RSpec視圖中,與視圖規範文件中的「之前」塊相比,示例對象還沒有完全初始化。因此,在「config.before」塊中,「模板」方法返回nil,因爲模板尚未初始化。你可以通過包括例如「把self.inspect」放在這兩個塊中。

在你的情況下,一個解決辦法是實現機規範將是spec_helper.rb定義

RSpec的2

module StubForgeryProtection 
    def stub_forgery_protection 
    view.stub(:request_forgery_protection_token) 
    view.stub(:form_authenticity_token) 
    end 
end 

RSpec.configure do |config| 
    config.include StubForgeryProtection 
end 

RSpec的1

module StubForgeryProtection 
    def stub_forgery_protection 
    template.stub!(:request_forgery_protection_token) 
    template.stub!(:form_authenticity_token) 
    end 
end 

Spec::Runner.configure do |config| 
    config.before(:each, :type => :views) do 
    extend StubForgeryProtection 
    end 
end 

,然後在每個之前(:每個)塊你想使用這個存根包括

before(:each) do 
    # ... 
    stub_forgery_protection 
    # ... 
end 
+0

感謝Raimonds,我最終做了類似的事情(順便說一下,@controller變量似乎沒有在配置中初始化,模板被定義爲@ controller.template,因此錯誤信息)。這感覺就像一個錯誤 – 2008-12-23 04:38:45

相關問題