rspec - 用法拉第和 Rspec 打桩

标签 rspec mocking stubbing faraday

我有一个看起来像这样的模型:

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、标题或正文的方法。

有没有更好的方法来编写我的 Rspec stub ?或者我是否能够以某种我无法理解的方式使用法拉第测试适配器?

谢谢!

最佳答案

我的 friend @n1kh1l 将我指向 and_yield Rspec 方法和 this SO post让我这样写我的测试:

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

关于rspec - 用法拉第和 Rspec 打桩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14329429/

相关文章:

python - 如何在 python 中修补模拟来自操作系统的多个调用?

unit-testing - typescript 中的Sinon stub 私有(private)变量?

node.js - 如何监视未导出的属性

ruby-on-rails - Capybara:如何测试页面的标题?

ruby-on-rails - 辅助规范上的 output_buffer 为空

ruby-on-rails - rspec 触发器 "DEPRECATION WARNING: The InstanceMethods module inside ActiveSupport::Concern will be no longer included automatically."

c# - 如何隔离 DbSet 等数据源?

testing - 当一个具体方法的签名引用另一个具体类型而不是它的接口(interface)时,我如何模拟多个类型?

testing - 清除 Equals 方法时 RhinoMocks 异常

ruby-on-rails - 更新 rspec gem 导致 'gem' 命令变得不稳定/有错误。帮助!