Search code examples
ruby-on-railsrspechttp-request

RSpec request spec for user_login via API


I'm trying to write a request spec for my user_login API, but can't figure out how to get a valid user that doesn't return a wrong username or password 401 invalid error.

Here is my spec:

require 'spec_helper'

describe User do
  subject(:user) do
    Program.create!(name: 'test', gender: 'Female', goal_id: '1', experience_id: '1')
    User.create!(email: 'test@test.com', password: '12345678', password_confirmation: '12345678', goal_id: '1', experience_level_id: '1', gender: 'Female')
  end

  it "is logged in" do
    post "/api/v1/login", user_login: {email: 'test@test.com', password: '12345678' }
    response.status.should be(201)
  end

My understanding was that creating a User in the subject line would mean that my test would run against that user. Any idea what I'm doing wrong here?


Solution

  • And Here is the answer

    require 'spec_helper'
    
    describe "sessions" do
      before do
        FactoryGirl.create(:program)
        @user = FactoryGirl.create(:user)
      end
    
        describe "user" do
          it "is logged in" do
            post "/api/v1/login", user_login: {email: @user.email, password: @user.password }
            response.status.should be(201)
          end
        end
    end
    

    I'm not totally sure what's different than what I was doing in the question. I replaced the subject block with a before block and moved the creation of the program and user into Factories.