ruby-on-rails – rspec-mocks’的双打仅设计为一个例子

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – rspec-mocks’的双打仅设计为一个例子前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个关于如何在示例之间分享rspec-mocks的双重问题.我正在用rspec-mocks 3.1.3编写一个新的rails应用程序.我习惯使用旧的(< 2.14,并且如果当前的rspec使用情况,我会尝试更新我的知识. 我有一个模型方法
def self.from_strava(activity_id,race_id,user)
  @client ||= Strava::Api::V3::Client.new(access_token: 'abc123')

  activity = @client.retrieve_an_activity(activity_id)

  result_details = {race_id: race_id,user: user}
  result_details[:duration] = activity['moving_time']
  result_details[:date] = Date.parse(activity['start_date'])
  result_details[:comment] = activity['description']
  result_details[:strava_url] = "http://www.strava.com/activities/#{activity_id}"


  Result.create!(result_details)
end

以下是规范:

describe ".from_strava" do
  let(:user) { FactoryGirl.build(:user) }
  let(:client) { double(:client) }
  let(:json_response) { JSON.parse(File.read('spec/support/strava_response.json')) }

  before(:each) do
    allow(Strava::Api::V3::Client).to receive(:new) { client }
    allow(client).to receive(:retrieve_an_activity) { json_response }
    allow(Result).to receive(:create!)
  end

  it "sets the duration" do
    expect(Result).to receive(:create!).with(hash_including(duration: 3635))
    Result.from_strava('123',456,user)
  end

  it "sets the date" do
    expect(Result).to receive(:create!).with(hash_including(date: Date.parse("2014-11-14")))
    Result.from_strava('123',user)
  end
end

当我自己运行单个测试时它很好,但是当我运行整个描述“.from_strava”时它会失败并显示消息

Double :client was originally created in one example but has leaked into another example and can no longer be used. rspec-mocks' doubles are designed to only last for one example,and you need to create a new one in each example you wish to use it for.

我理解它的含义,但肯定这是在2个例子中使用双重的合适用法.毕竟,客户端double对于示例并不重要,它只是我加载预设响应的一种方式.我想我可以使用WebMock,但这似乎非常低级,并且不能很好地转换为实际编写的代码.毕竟,每个例子我们应该只断言一件事.

我曾想过用一个调用替换客户端double

allow(Strava::Api::V3::Client).to receive_message_chain(:new,:retrieve_an_activity) { json_response }

但这似乎也不是正确的方法,因为文档声明receive_message_chain应该是代码气味.

因此,如果我不应该使用receive_message_chain,共享客户端double并遵循标准DRY原则那么我应该如何解决这个问题呢?

我会喜欢这方面的一些反馈.

谢谢,
戴夫

解决方法

surely this is an appropriate use of a double being used in 2 examples.

不,这不对. :)你正在尝试使用类变量;不这样做,因为变量不跨越示例.解决方案是每次设置客户端,即在每个示例中.

坏:

@client ||= Strava::Api::V3::Client.new(access_token: 'abc123')

好:

@client = Strava::Api::V3::Client.new(access_token: 'abc123')

猜你在找的Ruby相关文章