Charles
Charles

Reputation: 377

Pass instance variable to controller test in rspec?

I'm adding to test to an existing project. I have a user class that is assigned a unique url on create ad then is redirected to a path that contains that url.

I'm following the rspec book and wrote this test

it 'redirects to users#show' do
  post :create, user: attributes_for(:guest)
  expect(response).to redirect_to guest_path(:guest)
end

I get this back when I run the test.

Expected response to be a redirect to <http://test.host/guest/guest> but was a redirect to <http://test.host/guest/h7gutr1CMYxa5VNgWH5l1A>

The redirect the controller is sending back is correct but I am obviously writing the test incorrectly. How can I alter the expectation to pass the test?

Edit: Got a little closer, but still not there. Using

expect(response).to redirect_to guest_path(assigns(:user))

gives:

Expected response to be a redirect to <http://test.host/guest/1> but was a redirect to <http://test.host/guest/zaOVsiPBwQ4yNnC0mJNoNA>

using:

expect(response).to redirect_to guest_path(assigns(:user))

gives:

NoMethodError:
   undefined method `url' for :user:Symbol

Solution:

I couldn't figure out how to call methods on the instance variable. It's done like this:

it 'redirects to users#show' do
  post :create, user: attributes_for(:guest)
  expect(response).to redirect_to guest_path(assigns(:user).url)
end

Upvotes: 0

Views: 1333

Answers (1)

Marcelo De Polli
Marcelo De Polli

Reputation: 29291

Try this:

it 'redirects to users#show' do
  post :create, user: attributes_for(:guest)
  expect(response).to redirect_to guest_path(assigns(:guest))
end

In this case, assigns(:guest) will be equal to the instance variable with the same name as the arguments (:guest) that was returned by the request you're testing for.

Upvotes: 2

Related Questions