【发布时间】:2019-01-16 17:04:15
【问题描述】:
问题
我正在使用 RSpec 为使用 rails 制作的 api 设置测试。在其中一项测试中,我正在尝试添加一些身份验证标头,但是这些标头似乎无法满足我的请求。如何正确传递这些标头?
我需要传递 3 个标头(client、access-token 和 uid),以便系统将用户识别为已登录。如果我不通过,我会得到系统未登录error message
如果我在 postman 上手动尝试访问相同的端点,即我正在测试的端点,并简单地传递标头 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
结果
在我的 byebug 期间,如果我访问我要添加的变量 headers,我设置了正确的东西:
{"access-token"=>"eQV4yjzKU7cfCgD2kLcMPQ", "client"=>"FWJQNb-aRFD6lmYW1MU8Sw", "uid"=>"ericrice@feeney.com"}
注意:上面的值不是真实值,它们是由factory girl库生成的
但是,当我访问我的 请求标头时,它们并没有显示出来:
{"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"}
更新
第一次更新
我尝试从 type :api 切换到 type :request。 type :api 包括 Rack::Test::Methods,正如 @januszm 在评论 here 中所指出的那样,这弄乱了我的响应变量。但是,起初这似乎对我的情况没有任何影响。但我坚持测试并意识到这确实解决了我的问题。
【问题讨论】:
标签: ruby-on-rails rspec rspec-rails