Reputation: 1956
I have the following test written in RSpec:
describe '#create' do
...
it 'redirects users to profile page' do
response.should redirect_to user_path(user)
end
...
...
And the following in my UsersController
:
def create
@user = User.new(params[:user])
if @user.save
redirect_to user_path(@user)
end
end
Does anyone know why this is returning the following error:
NameError: undefined local variable or method 'user'
I also tried changing this to be root_url
in both cases instead of user_path(user)
and it gave a different error saying:
Expected response to be a <:redirect>, but was <200>
Does anyone know what the issue might be? I have double-checked my code and have seen similar questions posted online, but haven't been able to find a solution. Thanks in advance for any help!
Upvotes: 0
Views: 1804
Reputation: 1956
It turns out that assigns
just creates an instance variable and doesn't populate it without having another post :create
above it.
So, for future reference, here's the correct code:
it 'redirects to the users profile page' do
post :create, user: attributes_for(:user)
response.should redirect_to user_path(assigns :user)
end
However, you must use the assigns :user
as Mori suggested in order to create the instance variable in the second part. E.G. You can't simple do user_path(:user)
or user_path(@user)
.
Hope this helps someone in the future!
Upvotes: 0
Reputation: 27789
You can use Rspec Rail's assigns
method to access controller instance variables:
it 'redirects users to profile page' do
response.should redirect_to user_path(assigns :user)
end
Here assigns :user
is equivalent tocontroller.instance_variable_get :@user
.
As per @Justin's comment below, he was also missing the line to call the controller action:
post :create, user: attributes_for(:user)
Upvotes: 1