【发布时间】:2023-01-08 13:27:18
【问题描述】:
我正在编写将调用某些第 3 方 API 的代码。所以,我正在使用 API_HELPER 模块来调用第 3 方 api。
module ApiHelper
def self.get_header(header)
@request['Accept'] = header[:accept].blank? ? 'application/json' : header[:accept]
@request['Content-Type'] = header[:content_type].blank? ? 'application/json' : header[:content_type]
end
end
这是这个帮助文件的 Rspec:
describe '.get_header' do
let(:request) { double('request') }
before do
allow(ApiHelper).to receive(:get_header).and_call_original
allow(ApiHelper).to receive(:instance_variable_get).and_return(request)
allow(request).to receive(:[]=)
end
context 'when header values are provided' do
let(:header) { { accept: 'application/json', content_type: 'application/json' } }
it 'sets the Accept and Content-Type header values' do
ApiHelper.get_header(header)
expect(request).to have_received(:[]=).with('Accept', 'application/json')
# expect(request).to have_received(:[]=).with('Content-Type', 'application/json')
end
end
context 'when header values are not provided' do
let(:header) { {} }
it 'sets default values for the Accept and Content-Type headers' do
ApiHelper.get_header(header)
expect(request).to have_received(:[]=).with('Accept', 'application/json')
expect(request).to have_received(:[]=).with('Content-Type', 'application/json')
end
end
end
但是我运行这个规范,它显示错误:
Failures:
1) ApiHelper.get_header when header values are provided sets the Accept and Content-Type header values
Failure/Error: expect(request).to have_received(:[]=).with('Accept', 'application/json')
(Double "request").[]=("Accept", "application/json")
expected: 1 time with arguments: ("Accept", "application/json")
received: 0 times
# ./spec/helpers/api_helper_spec.rb:41:in `block (4 levels) in <top (required)>'
2) ApiHelper.get_header when header values are not provided sets default values for the Accept and Content-Type headers
Failure/Error: expect(request).to have_received(:[]=).with('Accept', 'application/json')
(Double "request").[]=("Accept", "application/json")
expected: 1 time with arguments: ("Accept", "application/json")
received: 0 times
# ./spec/helpers/api_helper_spec.rb:51:in `block (4 levels) in <top (required)>'
Finished in 0.23741 seconds (files took 1.39 seconds to load)
4 examples, 2 failures
我不明白什么会更正此代码的 rspec。
【问题讨论】:
标签: ruby-on-rails ruby rspec rspec-rails