views:

201

answers:

2

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"&gt;redirected&lt;/a&gt;.&lt;/body&gt;&lt;/html&gt;'

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
A: 

By definition, you are performing a unit test on the controller and therefore should not be trying to see what's in the response, only that the correct action happened and did everything it was supposed to do. Testing the contents of the response is a job for an integration test like Cucumber.

Warren
Thanks for the response. That makes sense, however I created a simpler test to see if I could get things working. I edited it in to the bottom of my question.
NudeCanalTroll
A: 

I'm confused why your test output says 'ApiController calling the test() method...' when your example seems to be for TestController. I've run a couple of examples of my own and I seem to get the correct results. I suggest trying the Ruby debugger (gem ruby-debug) to diagnose this. That way you can confirm that the proper code is being called as well as interactively check values.

Warren
Oops, the output is actually saying TestController, not ApiController. That was a copy and paste error on my part, my mistake.
NudeCanalTroll
OK, but if I recreate exactly what you have above, the test passes for me. FYI, I'm running under Ruby v1.8.7 / Rails 2.3.4 / rspec 1.2.9
Warren