开发者

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
'TestControl开发者_开发知识库ler calling the test() method should set the flash notice' FAILED
expected blank? to return false, got true


Change your assertion to be

response.should be_redirect

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


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.


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.

Essentially, try asserting that the controller attempted a redirect.

@response.should be_redirect
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜