Expected response to be a <redirect>, but was <200>

Opy Osegs picture Opy Osegs · Sep 4, 2015 · Viewed 12.1k times · Source

I'm trying to testing the create action in the UsersController where the user is created with a profile; then the user is redirected to the user's profile page, but i get the error Expected response to be a <redirect>, but was <200>.

CREATE ACTION IN USER CONTROLLER

def create
  @user = User.new(user_params)
  if @user.save
    log_in @user
    flash[:success] = "Welcome to the Mini Olympics"
    redirect_to user_profile_path(current_user, @profile)
  else
    render 'new'
  end
end

SIGNUP TEST USING VALID INFORMATION

test "valid signup information" do
  get signup_path
  assert_difference 'User.count', 1 do
    post users_path, user: @user.attributes
    @user.build_profile(name: "Micheal Example", street: "24 Martins St.", city: "Waterloo", state: "AW", zipcode: "22456")
    @user.save
    #assert_redirected_to user_profile_path(@user)
    assert_redirected_to @user.profile
  end
  assert_template 'profiles/show'
  assert is_logged_in?
end

Answer

zetetic picture zetetic · Sep 4, 2015

The error message means that the create action is failing, and instead of redirecting to the user's profile (status 302), it renders the form again (status 200).

As to why it fails, that is unclear. The test appears to confuse the value of @user in the controller, with the value of @user in the test, which are two completely different objects.

When testing an action, you pass the values in through the params hash, as you do above in the line:

post users_path, user: @user.attributes

But the test then sets the value of @user again, for no good reason. It's not clear to me where the original value of @user (the one in the test) gets its attributes.

You probably want to do something like this:

 assert_difference 'User.count', 1 do
   user = User.new
   user.build_profile(name: "Micheal Example", street: "24 Martins St.", city: "Waterloo", state: "AW", zipcode: "22456")
   post users_path, user: user.attributes
   assert_redirected_to user.profile
 end

The local variable user is just a convenience for generating the values for the attributes hash. You could just as easily assign the attributes directly to a hash and pass them to post.