How do i set a request.referrer inside my RSpec?

北城余情 提交于 2019-12-31 17:51:30

问题


I am trying to avoid using my session[:referred_by], and would like to use the request.referrer. However, my RSpec tests fail because the TestRequest does not store a request.referrer

So I have to do the following in order for Rspec tests to work. Is there a way to make it better:

referrer = request.referrer ? request.referrer : '/'
redirect_to referrer, :alert => error_message

回答1:


Mock it:

specify 'foo' do
  controller.request.should_receive(:referer).and_return('http://example.com')
  # get whatever
end

Or if you don't care if it doesn't get called, stub it:

controller.request.stub referer: 'http://example.com'



回答2:


ActionDispatch::TestRequest extends ActionDispatch::Request that extends Rack::Request.

The method is defined as follows

def referer
  @env['HTTP_REFERER']
end
alias referrer referer

As far as I remember, you can access the environment variable in the RSpec test by using request.env. It means, it should be possible to set something like

request.env['HTTP_REFERER'] = 'http://example.com'

Of course, it depends on the type of RSpec example group you are using.




回答3:


On Rails 5 the accepted solution doesn't seem to work anyore, but setting request.env['HTTP_REFERER'] directly, as Simone Carletti suggests, works.




回答4:


With Rails4/Rspec3, in request specs, request is not available until you make an http call. But you can assign request.referer by doing something like this:

get '/posts', {}, { referer: 'http://example.com' }



回答5:


Solution for Rails 5.2+ & RSpec 3.8+

get :endpoint, params: {}, headers: { 'HTTP_REFERER' => 'stackoverflow.com' }



回答6:


For anyone else Googling this, you can also stub the request in a helper spec like this:

allow(view).to receive_message_chain(:request, :referrer).and_return("http://example.com")


来源:https://stackoverflow.com/questions/12591763/how-do-i-set-a-request-referrer-inside-my-rspec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!