Search code examples
ruby-on-railstestinghttp-redirectrspeccontrollers

Rails: When testing controllers with RSpec, how do I stop them from redirecting?


I have controller methods that look like this:

class TestController < ApplicationController
  def testAction
    render :json => { 'success'=>1 }.to_json
  end
end

When I load this action in the browser, I get what I expect: {"success":1}

When testing with RSpec, however, response.body gives me '<html><body>You are being <a href="https://test.host/test/testAction">redirected</a>.</body></html>'

I've noticed that this weird redirection is happening with all of my controllers. How can I stop this redirection from happening, so I can run checks on the response body?

Thanks!

----------------------- EDIT:

Any idea why the following test failure is happening?

# app/controllers/test_controller.rb
def test
  flash[:notice] = 'test'
end

# spec/controllers/test_controller_spec.rb
describe TestController, "calling the test() method" do
  it "should set the flash notice" do
    put :test
    flash[:notice].should_not be_blank
  end
end

# result
'TestController calling the test() method should set the flash notice' FAILED
expected blank? to return false, got true

Solution

  • Change your assertion to be

    response.should be_redirect
    

    At least, if it's doing the right thing :)