我有一个看起来像这样的模型:
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、标头或正文,因为它们是通过一个块。我尝试使用 Faraday 测试适配器,但我也没有看到任何测试 URL、标头或正文的方法。
有没有更好的方法来编写我的 Rspec 存根?或者我是否能够以某种我无法理解的方式使用法拉第测试适配器?
Thanks!
我的朋友@n1kh1l 向我指出了and_yield
Rspec 方法和这个帖子 https://stackoverflow.com/questions/12641631/rspec-use-test-double-as-block-argument这让我可以像这样编写测试:
require 'spec_helper'
describe Gist do
context '.create' do
it 'POSTs a new Gist to the user\'s account' do
gist = {:public => 'true',
:description => 'a test gist',
:files => {'test_file.rb' => {:content => 'puts "hello world!"'}}}
request = double
request.should_receive(:url).with('https://api.github.com/gists')
headers = double
headers.should_receive(:[]=).with('Authorization', "Basic " + Base64.encode64("#{GITHUB_USERNAME}:#{GITHUB_PASSWORD}"))
request.should_receive(:headers).and_return(headers)
request.should_receive(:body=).with(gist.to_json)
Faraday.should_receive(:post).and_yield(request)
Gist.create(gist)
end
end
end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)