如何使用Rspec和Rails模拟一个类?

Dav*_*ave 7 rspec ruby-on-rails mocking ruby-on-rails-5

我正在使用Rails 5和Rspec 3.如何在Rspec方法中模拟一个类?我有以下课程

require 'rails_helper'

describe CryptoCurrencyService do

  describe ".sell" do

    it "basic_sell" do
      last_buy_price = 3000
      last_transaction = MoneyMakerTransaction.new({
        :transaction_type => "buy",
        :amount_in_usd => "100",
        :btc_price_in_usd => "#{last_buy_price}"
      })
      @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)

      allow(@client).to receive(:sell_price).and_return({"base"=>"BTC", "currency"=>"USD", "amount"=>"#{sell_price}"})

      svc = CryptoCurrencyService.new
      svc.sell(last_transaction)
      last_transaction = MoneyMakerTransaction.find_latest_record
      assert last_transaction.transaction_type, "sell"
    end

  end

end
Run Code Online (Sandbox Code Playgroud)

而不是实际实例化行中的"Coinbase :: Wallet"类

@client = Coinbase::Wallet::Client.new(api_key: ENV['COINBASE_KEY'], api_secret: ENV['COINBASE_SECRET'])
Run Code Online (Sandbox Code Playgroud)

我想创建mock taht然后我可以插入到我正在测试的服务类中.就目前而言,当我运行时,实际的底层类被实例化,导致运行时错误...

  1) CryptoCurrencyService.sell basic_sell
     Failure/Error: payment_method = client.payment_methods()[0]

     Coinbase::Wallet::AuthenticationError:
       invalid api key
Run Code Online (Sandbox Code Playgroud)

Tar*_*ast 7

rspec模拟和存根可以在任何类上使用.例如:

coinbase_mock = double(api_key: ENV['COINBASE_KEY'], api_secret: ENV['COINBASE_SECRET'])
expect(Coinbase::Wallet::Client).to_receive(:new).and_return(coinbase_mock)
Run Code Online (Sandbox Code Playgroud)

然后你可以添加你喜欢的任何东西,coinbase_mock以便它像你需要的类一样嘎嘎叫... :)