问题描述
我有一个看起来像这样的模型:
I have a model that looks like this:
class Gist
def self.create(options)
post_response = Faraday.post do |request|
request.url 'https://api.github.com/gists'
request.headers['Authorization'] = "Basic " + Base64.encode64("#{GITHUB_USERNAME}:#{GITHUB_PASSWORD}")
request.body = options.to_json
end
end
end
和如下所示的测试:
require 'spec_helper'
describe Gist do
context '.create' do
it 'POSTs a new Gist to the user\'s account' do
Faraday.should_receive(:post)
Gist.create({:public => 'true',
:description => 'a test gist',
'files' => {'test_file.rb' => 'puts "hello world!"'}})
end
end
end
不过,此测试并不能真正让我满意,因为我所测试的只是我正在用Faraday进行一些POST,但由于它们是URL,标头或正文,因此我实际上无法对其进行测试用块传递.我尝试使用法拉第测试适配器,但也没有任何方法可以测试URL,标头或正文.
This test doesn't really satisfy me, though, as all I'm testing is that I'm making some POST with Faraday, but I can't actually test the URL, headers, or body, since they're passed in with a block. I tried to use the Faraday test adaptor, but I don't see any way of testing the URL, headers, or body with that, either.
是否有更好的方式编写Rspec存根?还是我可以以某种我无法理解的方式使用法拉第测试适配器?
Is there a better way to write my Rspec stub? Or am I able to use the Faraday test adaptor in some way I haven't been able to make sense of?
谢谢!
推荐答案
在您的代码中:
Faraday.post do |req|
req.body = "hello world"
req.url = "http://example.com/"
end
Faraday.get do |req|
req.url = "http://example.com/"
req.params['a'] = 1
req.params['b'] = 2
end
在RSpec文件中:
stub = stub_request(:post, "example.com")
.with(body: "hello world", status: 200)
.to_return(body: "a response to post")
expect(stub).to have_been_requested
expect(
a_request(:get, "example.com")
.with(query: { a: 1, b: 2 })
).to have_been_made.once
这篇关于与法拉第和Rspec存根的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!