Why isn't my mock getting used in my minitest test run?

Viewed 199

I'm trying to write a test with Rails 5 and using minitest Here is my test code ...

@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)

but when it esxecutes on the below what is printing out is not my mocked sell price of "4000", it is the actual sell price being returned by the client ...

  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}"

How do I get my mock worked into things?

1 Answers

Object#stub stubs method value for duration of the block, as documentation states

Add a temporary stubbed method replacing name for the duration of the block. If val_or_callable responds to #call, then it returns the result of calling it, otherwise returns the value as-is. Cleans up the stub at the end of the block.

Answering to your original question:

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