I\'m trying to test a controller and I got this error. I understand the error, but don\'t know how to fix it.
test: on CREATE to :user with completely invali
Currently, I used Rails 5.2.1, my approach to stub request referer inside controller is like below:
let(:stub_referer) { some_path(some_param) }
before do
request.headers.merge! referer: stub_referer
get :some_action, format: :html
end
Most straight forward solution to the above problem is to make the request with associated headers. Rails will automatically read this header.
post '/your-custom-route', {}, {'HTTP_REFERER': 'http://www.your-allowed-domain.com'}
In response to the question:
Why doesn't this work:
setup { post :create, { :user => { :email => 'invalid@abc' } },
{ 'referer' => '/sessions/new' } }
It doesn't work because the Rails doc you linked to documents a different class than the one you're probably using.
You linked to ActionController::Integration:Session
. I'm guessing that you're writing a functional test (if you're using Test::Unit) or a controller test (if you're using Rspec). Either way, you're probably using ActionController::TestCase
or a subclass thereof. Which, in turn, includes the module ActionController::TestProcess
.
ActionController::TestProcess
provides a get
method with different parameters than the get
method provided by ActionController::Integration:Session
. (Annoying, eh?) The method signature is this:
def get(action, parameters = nil, session = nil, flash = nil)
Sadly, there is no headers parameter. But at least setting @request.env['HTTP_REFERER']
works.
The accepted answer doesn't work for integration tests because the @request
variable doesn't exist.
According to RailsGuides, you can pass headers to the helpers.
test "blah" do
get root_path, {}, {'HTTP_REFERER' => 'http://foo.com'}
...
end
test "blah" do
get root_path, params: { id: 12 }, headers: { "HTTP_REFERER" => "http://foo.com" }
...
end
setup do
@request.env['HTTP_REFERER'] = 'http://test.com/sessions/new'
post :create, { :user => { :email => 'invalid@abc' } }
end
In Rails 2.2.2, the above block never ran actual test. Saying that
post :create, { :user => { :email => 'invalid@abc' } }
line did not run. You can simply get rid of setup block and use
@request.env['HTTP_REFERER'] = 'http://test.com/sessions/new'
post :create, { :user => { :email => 'invalid@abc' } }
instead. And it should set the referer
Their recommendation translates to the following:
setup do
@request.env['HTTP_REFERER'] = 'http://test.com/sessions/new'
post :create, { :user => { :email => 'invalid@abc' } }
end