2009-02-26 22 views
6

爲了避免在每次controller_spec文件創建加設置在全球前HTTP_REFERER(:所有)在Rspec的

request.env["HTTP_REFERER"] = '/' 

一個塊之前,我曾試圖把它添加到全局配置(在spec_helper.rb)

config.before(:each) {request.env["HTTP_REFERER"] = '/'} 

的問題是,我得到以下錯誤:

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

有任何人任何POIN ters關於如何正確實現這個?

乾杯!

回答

12

你試過

config.before(:type => :controller) do 
    request.env["HTTP_REFERER"] = "/" 
    end 
+0

乾杯 - 完美的作品! – Codebeef 2009-02-27 10:49:32

1

我注意到馬特的答案是2年前,我不知道他在用什麼「RSpec的」版本。 但對於我而言,我的RSpec版本1.3.2 =和代碼段不起作用(總是得到一個錯誤:

You might have expected an instance of Array. 
The error occurred while evaluating nil.<< 
    from /usr/lib/ruby/gems/1.8/gems/rspec-1.3.2/lib/spec/runner/configuration.rb:181:in `__send__' 
    from /usr/lib/ruby/gems/1.8/gems/rspec-1.3.2/lib/spec/runner/configuration.rb:181:in `add_callback' 
    from /usr/lib/ruby/gems/1.8/gems/rspec-1.3.2/lib/spec/runner/configuration.rb:101:in `before' 
... 

),直到我改變了一下:

# here the ":each" symbol is very important and necessary. 
# :type => :controller is the "option" 
config.before(:each, :type => :controller) do 
    request.env["HTTP_REFERER"] = "/" 
end 

參考rspec-1.3.2的文檔:

append_before(scope = :each, options={}, &proc) 
Appends a global before block to all example groups. scope can be any of 
:each (default), :all, or :suite. 
When :each, the block is executed before each example. 
When :all, the block is executed once per example group, before any of its examples are run. 
When :suite the block is run once before the entire suite is run.