Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSpec redirect_to and return vs. redirect_to && return

I have a controller that redirects at certain points under certain conditions. When I pass parameters to my spec helper methods in my controller spec (using the latest RSpec) to trigger these conditions I get a

ActionView::MissingTemplate

error. Under closer examination when I am supposed to redirect I do a line like the following:

redirect_to root_path && return

And then an exception is thrown in my test suite. I put a break point in the index function of the controller that should be called (that the route I'm redirecting to is pointing to) and it is never called in my test suite. This code seems to work when I just run it in my development environment and on production but for this test it just won't budge. Any ideas?

My test looks something like this:

describe TestController do
  it 'redirects properly with failure' do
    get :create, provider: 'test', error: 'access_denied'
    expect(response.body).to match 'test'
  end
end

EDIT:

Update!

It seems that changing my redirect to

redirect_to root_path and return

works in RSpec.

I do not know why the precedence of the && operator is breaking the spec. Does anyone have an explanation of what is going on here?

like image 225
Ben Nelson Avatar asked Sep 25 '15 00:09

Ben Nelson


3 Answers

As per the Rails guide:

Make sure to use and return instead of && return because && return will not work due to the operator precedence in the Ruby Language.

If you prefer to use &&, enclose the arguments to render in parentheses:

redirect_to(root_path) && return
like image 190
henrebotha Avatar answered Nov 12 '22 10:11

henrebotha


The difference&& has higher precedence than and. The high precedence results in ruby parsing this as

redirect_to(root_path && return)

Methods must of course evaluate their arguments before the method itself is called, so in this case redirect_to is never called, because ruby hits the return first.

On the other hand, the lower precedence of and means that it is parsed as

(redirect_to root_path) and return

Which is what you wanted - first do the redirect and then return.

like image 6
Frederick Cheung Avatar answered Nov 12 '22 10:11

Frederick Cheung


The template must exist when you test your controller since views are stubbed by default. See the RSpec Documentation

So make sure you have the template present for your controller action.

like image 1
K M Rakibul Islam Avatar answered Nov 12 '22 12:11

K M Rakibul Islam