mercredi 24 juin 2020

Rails/Rspec integration tests with rspec and requests - route not matches for second test

I can't understand why my second test does not work.

This works perfectly fine:

require 'rails_helper'
require 'spec_helper'

RSpec.configure do |config|
    config.include Devise::Test::IntegrationHelpers
end

RSpec.describe 'GET /users/:id', type: :request do

    before(:all) do
        @user = User.find_by(email: "user@dev.test")
        sign_in @user
    end
        
    it "returns a user object" do
        get "/users/#{@user.id}.json"
        expect(response.status).to eq 200
        expect(response).to have_http_status(:success) 
        expect(response.content_type).to eq("application/json; charset=utf-8")
        expect(JSON.parse(response.body)["successful"]).to eql(true)
    end

end

but, if I add a second request in the same test like this:

require 'rails_helper'
require 'spec_helper'

RSpec.configure do |config|
    config.include Devise::Test::IntegrationHelpers
end

RSpec.describe 'GET /users/:id', type: :request do

    before(:all) do
        @user = User.find_by(email: "user@dev.test")
        sign_in @user
    end
        
    it "returns a user object" do
        get "/users/#{@user.id}.json"
        expect(response.status).to eq 200
        expect(response).to have_http_status(:success) 
        expect(response.content_type).to eq("application/json; charset=utf-8")
        expect(JSON.parse(response.body)["successful"]).to eql(true)
    end

    it "returns another user object" do
        get "/users/#{@user.id}.json"
        expect(response.status).to eq 200
        expect(response).to have_http_status(:success) 
        expect(response.content_type).to eq("application/json; charset=utf-8")
        expect(JSON.parse(response.body)["successful"]).to eql(true)
    end

end

the test fails with error: ActionController::RoutingError: No route matches [GET] "/users/2.json"

as you can see both tests are the same, but for some reason the second test always fail.

Aucun commentaire:

Enregistrer un commentaire