The instance @user
at unit tests is not the same instance @user
at controller, but they're used for similar reasons.
@
signify instance variables, which are available in all other methods of the instance object.
If in a controller you have
def new
@user = User.new
apply_another_value_to_user
end
def apply_another_value_to_user
@user.nickname = 'Zippy'
end
That works.
If instead you do...
def new
user = User.new
apply_another_value_to_user
end
def apply_another_value_to_user
user.nickname = 'Zippy'
end
You will get an error "undefined local variable or method 'user'" because user
is only defined for use within the new
method.
unit tests use @user
to ensure a user object can be shared by different methods in the test instance. Controllers use @user
to ensure a user object can be shared by different methods (and views) in the controller instance. It may be that during a test a controller instance is initialized and both @user
instance variables happen to be created but they are not the same variable.
This is why in a test, to access a controller instance variable, you can't use @user
directly, you have to use assigns(:user)
which references the controller instance variable.
expects(assigns(:user).not_to be_nil