Question

I'm running an integration test using RSpec on a Rails 4 API running rails-api. I want to see that if the wrong email address is passed to the login controller I get a 401 back.

Here is my expectation

it "should throw invalid login for user with invalid email" do
  post "/api/v1/users/sign_in", uname: "wrong_email@wrong.com", password: "12234"

  expect(response).to eq(401)

end

In my controller I have:

def create
  @user = User.find_by_email(params[:uname])
  if(@user && @user.valid_password?(params[:password]))
  ....
end

This works fine in the browser and I get a 401 back. But when I run rspec it will just hang and never report failure or pass, just sit there with no error. The crux of the problem appears to be the if(@user) part. If I remove that then the test will at least run.

I checked log/test.log and I can see Completed 401 Unauthorized in 14ms (Views: 0.2ms | ActiveRecord: 2.8ms) in the log.

Update

To clarify, this is a request spec. I'm testing that the consumer of the API would receive a 401 response in the case of an invalid email.

Was it helpful?

Solution

Try

 expect(response.response_code).to eq 401

or

 expect(response.status).to eq 401
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top