vendredi 10 juillet 2015

RSpec stubbing only works for first request, does not work for subsequent requests

I am writing request specs for my app and I am having an issue with stubbing for multiple requests.

My test:

it "adding a text response element to the campaign" do
  TextResponsesController.any_instance.stub(:current_user).and_return(@user)

  get new_campaign_text_response_path(@campaign)
  expect(response).to render_template(:new)

  post "/campaigns/#{@campaign.id}/text_responses", { :text_response => {:name => "test", :campaign_id => @campaign.id, :keyword => @campaign.keyword, :message => "testing", :clip_id => Content::DEFAULT[1], :sender_name => "tester", :start_date => Time.now, :end_date => Time.now + 86400} }
  expect(@campaign.components.first.class).to equal TextResponse
end

In this example, I am stubbing the :current_user method on any instance of the controller so it can emulate a logged in user, otherwise it would just redirect to the sign in page.

The issue is that, by outputting the response body after each request, I have discovered that the first get request is successfully made, but the post request fails as it gets redirected to the sign in page.

Things I have tried:

1) Commenting out the get request. This allows the post request to succeed (no longer redirecting to the sign in page).

2) Putting the two requests in separate "it" blocks with the stub defined in each block. Does not make a difference, first request works but the second one gets redirected.

I am very confused since the stub is clearly working when there is only one request, but fails for any subsequent requests. I've been trying to solve this issue for the whole day, and I am finally at a loss.

Any help would be greatly appreciated.

Aucun commentaire:

Enregistrer un commentaire