简体   繁体   中英

Devise & Factorybot authentication for RSpec POST request

Setup using devise_token_auth, Factorygirl, and RSpec.

Trying to sign in a user, and make a post request, but I am getting 401 unauthorized response.

/spec/controllers/scripts_controller_spec.rb

module Api::V1
RSpec.describe ScriptsController, type: :controller do

  let(:user) { FactoryBot.create(:user)}

  let(:valid_attributes) {
    {name: 'YWoodcutter', skill: 'Woodcutting', bot_for: 'TRiBot', game_for: "Oldschool Runescape 07", user_id: user.id}
  }
...
describe "POST #create" do
    context "with valid params" do
      it "creates a new Script" do
        sign_in user
        expect {
          post :create, params: {script: valid_attributes}
        }.to change(Script, :count).by(1)
      end

      it "renders a JSON response with the new script" do
        sign_in user
        post :create, params: {script: valid_attributes}
        expect(response).to have_http_status(:created)
        expect(response.content_type).to eq('application/json')
        expect(response.location).to eq(script_url(Script.last))
      end
    end

RSpec Test Results: Failures:

1) Api::V1::ScriptsController POST #create with valid params creates a new Script Failure/Error: expect { post :create, params: {script: valid_attributes} }.to change(Script, :count).by(1)

  expected #count to have changed by 1, but was changed by 0 # ./spec/controllers/scripts_controller_spec.rb:72:in `block (4 levels) in <module:V1>' 

2) Api::V1::ScriptsController POST #create with valid params renders a JSON response with the new script Failure/Error: expect(response).to have_http_status(:created) expected the response to have status code :created (201) but it was :unauthorized (401) # ./spec/controllers/scripts_controller_spec.rb:80:in `block (4 levels) in '

Curious as to why the POST #create didn't fire. I essentially used the same values from my seed data, which works fine.

Also wondering why request is unauthorized, even after calling Devise's signn_in user.

Thank you.

Edit: The Devise wiki mentions mappings should I be calling this line somwhere?

@request.env["devise.mapping"] = Devise.mappings[:user]

devise_token_auth requires you to include the token in the headers, I put a helper in the support folder:

def auth_request(user)
  sign_in user
  request.headers.merge!(user.create_new_auth_token)
end

and then in your specs call auth_request user instead of sign_in user

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM