【问题标题】:Why isn't my mock getting used in my minitest test run?为什么我的模拟没有在我的 minitest 测试运行中使用?
【发布时间】:2017-09-29 19:18:17
【问题描述】:

我正在尝试使用 Rails 5 编写测试并使用 minitest 这是我的测试代码...

@client = Coinbase::Wallet::Client.new(api_key: ENV['COINBASE_KEY'], api_secret: ENV['COINBASE_SECRET'])
sell_price = 4000
assert sell_price > last_buy_price * (1 + MoneyMakerThreshhold.find_buy.pct_change)
@client.stub :sell_price, "USD" do
  {"base"=>"BTC", "currency"=>"USD", "amount"=>"#{sell_price}"}
end

svc = CryptoCurrencyService.new
svc.sell(last_transaction)

但是当它在下面执行时,打印出来的不是我模拟的“4000”卖价,而是客户返回的实际卖价......

  def sell(last_transaction)
    client = Coinbase::Wallet::Client.new(api_key: ENV['COINBASE_KEY'], api_secret: ENV['COINBASE_SECRET'])
    sell_price = client.sell_price(currency: 'USD').amount
    puts "buy: #{last_transaction.btc_price_in_usd} sellprice: #{sell_price} last:#{last_transaction.btc_price_in_usd}"

如何让我的模拟变成现实?

【问题讨论】:

  • 你使用哪个版本的 coinbase-ruby?

标签: mocking ruby-on-rails-5 minitest stub


【解决方案1】:

Object#stub 存根方法值用于块的持续时间,如文档所述

在块的持续时间内添加一个临时存根方法替换名称。如果 val_or_callable 响应 #call,则返回调用它的结果,否则按原样返回值。清理块末尾的存根。

回答你原来的问题:

client.stub :sell_price, {"base"=>"BTC", "currency"=>"USD", "amount"=>"#{sell_price}"} do
  svc = CryptoCurrencyService.new
  svc.sell(last_transaction)  
end

【讨论】:

  • 希望您能收到此评论,因为我的回复有点晚。您是说用您提供的内容替换我以“@client.stub ...”开头的代码吗?
  • @Dave 是的。并将您的断言和语句放入块中
猜你喜欢
  • 1970-01-01
  • 2014-04-21
  • 1970-01-01
  • 2014-05-24
  • 2021-08-14
  • 1970-01-01
  • 2021-09-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多