I'm setting up tests, using RSpec, for an api, made with rails. In one of the tests, I'm trying to add some authentication headers, however it appears the headers won't add up to my request. How can I properly pass those headers?
I need to pass 3 headers (client, access-token and uid) so the system recognizes the user as logged. If I don't pass, I get the system not logged error message
If I manually try accessing the same endpoint, the one I'm making the test for, on postman and simply pass the headers, it works
RSpec.describe Api::V1::Profiles::CreditCardsController, type: :api do
describe 'POST /api/v1/profiles/credit_cards' do
let!(:profiles) {FactoryGirl.create_list(:profile, 1)}
it 'Usuário cadastrando cartão no sistema' do
number = Faker::Stripe.valid_card
params = {
:number => number,
:expiration_date => Faker::Stripe.year + '/' + Faker::Stripe.month,
:brand => 'Visa',
:proper_name => Faker::Name.name,
:cvv => Faker::Stripe.ccv,
}
headers = auth_headers(profiles[0])
requisicao = post '/api/v1/profiles/credit_cards', params, headers
# byebug
expect(last_response.status).to eq(200)
end
end
During my byebug if I access my variable headers, which is the one I'm trying to add, I have the right things set:
{"access-token"=>"eQV4yjzKU7cfCgD2kLcMPQ", "client"=>"FWJQNb-aRFD6lmYW1MU8Sw", "uid"=>"[email protected]"}
Note: the values above aren't real values, they were generated by factory girl library
However, when I access my request headers they don't show up:
{"X-Frame-Options"=>"SAMEORIGIN", "X-XSS-Protection"=>"1; mode=block", "X-Content-Type-Options"=>"nosniff", "Content-Type"=>"application/json; charset=utf-8", "Cache-Control"=>"no-cache", "X-Request-Id"=>"0ed4657c-507d-4033-bc20-81d452de0d1b", "X-Runtime"=>"0.004898", "Date"=>"Wed, 16 Jan 2019 16:43:03 GMT", "X-Rack-Cache"=>"pass", "Vary"=>"Origin", "Content-Length"=>"59"}
I tried switching from type :api to type :request. The type :api was including Rack::Test::Methods, which was messing up my response variable, as pointed by @januszm in a comment here. However, that didn't seem to have any effect with my situation, at first. But them I insisted on testing and realized that did solve my problem.
Switching from type :api to type :request gave me access to the request and response variables, which, before, I had to created variables myself to try access them.
When using type :api, I had access to last_response instead of response, because my type :api was including Rack::Test::Methods, which was messing up those variables (response and request), as according to this post.
When I switched to type :request, and was no longer importing Rack::Test::Methods, I was able to access request variable and saw that the desired headers were correctly added.