Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting the HTTP_REFERER in a global before(:all) in Rspec

In order to avoid adding

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

to a before block on every controller_spec file I create, I have tried to add this to the global config (in spec_helper.rb)

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

The problem is, I get the following error:

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

Has anyone any pointers on how to implement this correctly?

Cheers!

like image 890
Codebeef Avatar asked Feb 26 '09 11:02

Codebeef


2 Answers

Have you tried

  config.before(:type => :controller) do
    request.env["HTTP_REFERER"] = "/"
  end
like image 168
Matt Darby Avatar answered Sep 19 '22 02:09

Matt Darby


I notice that Matt's answer was 2 years ago, I am not sure what "rspec" version he was using. but for my case, my rspec version=1.3.2, and the code segment doesn't work(always got an error:

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

), until I change it a bit:

# 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

refer to rspec-1.3.2's doc:

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.
like image 24
Siwei Avatar answered Sep 18 '22 02:09

Siwei