views:

368

answers:

2

Does anyone know how to make rspec follow a redirect (in a controller spec)? (e.g test/unit has follow_redirect!)

I have tried "follow_redirect!" and "follow_redirect" but only get

undefined method `follow_redirect!' for #<Spec::Rails::Example::ControllerExampleGroup::Subclass_1:0xb6df5294>

For example:
When I create an account the page is redirected to accounts page and my new account should be at the top of the list.

it "should create an account" do
  post :create, :name => "My New Account"
  FOLLOW_REDIRECT!
  response.code.should == "200"
  accounts = assigns[:accounts]
  accounts[0].name.should == "My New Account"
end

But FOLLOW_REDIRECT! needs to be changed to something that actually works.

+4  A: 

I think this is the default behavior for rspec-rails controller tests, in the sense that you can set an expectation on the response status and/or path, and test for success.

For example:

it "should create an account" do
  post :create
  response.code.should == "302"
  response.should redirect_to(accounts_path)
end
zetetic
Hi Zetetic. Thanks for your reply. What you describe in your answer would be the correct way to Verify that the response is a 302-redirect to the accounts_path. What I want to do is to follow the redirect to the accounts_path and verify the behaviour of that page. E.g. verify that my new account is listed there.
Jonas Söderström
I updated my question, hope you don't mind that I borrowed your example.
Jonas Söderström
Guess I misunderstood the question. Would `integrate_views` help in this situation?
zetetic
`integrate_views` does not seem to help. I still get "...You are being redirected..." response, but it was a good try
Jonas Söderström
+2  A: 

If you want to test the redirect you are moving outside of the rspec-rails domain.

You can use Webrat or some other integration-test framework to test this.

The easiest way to solve this without resorting to integration testing is probably to mock out the method that is causing the redirect.

andersjanmyr