2009-02-26 24 views
6

Để tránh thêmThiết HTTP_REFERER trong một toàn cầu trước (: tất cả) trong rspec

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

đến một trước khi khối trên tất cả các tập tin controller_spec tôi có thể tạo, tôi đã cố gắng để thêm video này vào cấu hình toàn cầu (trong spec_helper.rb)

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

vấn đề là, tôi nhận được lỗi sau:

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

có ai bất kỳ poin ters về cách thực hiện điều này một cách chính xác?

Chúc mừng!

Trả lời

12

Các bạn đã thử

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

Chúc mừng - Hoạt động hoàn hảo! – Codebeef

1

Tôi nhận thấy rằng câu trả lời của Matt là 2 năm trước, tôi không chắc chắn những gì "rspec" phiên bản ông đã sử dụng. nhưng đối với trường hợp của tôi, phiên bản của tôi rspec = 1.3.2, và đoạn mã không hoạt động (luôn luôn có một lỗi:

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' 
... 

), cho đến khi tôi thay đổi nó một chút:

# 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 

tham khảo tài liệu của 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. 
Các vấn đề liên quan