法拉第和RSpec打桩(Stubbing with Faraday and Rspec)

2019-08-06 21:06发布

我有一个模型,如下所示:

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

这个测试并没有真正满足我,不过,因为所有我测试的是我正在做一些POST法拉第,但我无法实际测试的URL,标题,或身体,因为他们与传递的块。 我试图用法拉第测试适配器,但我没有看到测试的URL,标题或正文与任何办法,无论是。

有没有更好的方式来写我的Rspec的存根? 还是我能够使用法拉第测试适配器在某些方面我一直没能做出的有意义吗?

谢谢!

Answer 1:

您可以使用优秀的WebMock库存根该请求已取得预期的要求和测试, 看文档

在您的代码:

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


Answer 2:

我的朋友@ n1kh1l向我指出的and_yield Rspec的方法和该SO后 ,让我写我的测试是这样的:

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


文章来源: Stubbing with Faraday and Rspec