Search code examples
ruby-on-railsrubyrspecrspec-rails

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?


Solution

  • 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