rspec should_receive不起作用,但期望工作

时间:2014-01-16 10:16:37

标签: ruby-on-rails rspec rspec-rails

我的课程如下

#bank.rb
class Bank
   def transfer(customer1, customer2, amount_to_transfer)
      if customer1.my_money >= amount_to_transfer
        customer1.my_money -= amount_to_transfer
        customer2.my_money += amount_to_transfer
      else
        return "Insufficient funds"
      end 
   end 
end

class Customer
  attr_accessor :my_money

  def initialize(amount)
    self.my_money = amount
  end 
end

我的spec文件如下所示:

#spec/bank_spec.rb
require './spec/spec_helper'
require './bank'

describe Bank do
  context "#transfer" do
    it "should return insufficient balance if transferred amount is greater than balance" do
    customer1 = Customer.new(500)
    customer2 = Customer.new(0)

    customer1.stub(:my_money).and_return(1000)
    customer2.stub(:my_money).and_return(0)

    expect(Bank.new.transfer(customer1, customer2, 2000)).to eq("Insufficient funds")
    expect(customer1).to have_received(:my_money) # This works
    customer1.should_receive(:my_money) #throws error 
   end 
  end 
end

根据https://relishapp.com/rspec/rspec-mocks/v/2-14/docs/message-expectationsexpectshould_receive都相同,但expectshould_receive更具可读性。但为什么它失败了?提前谢谢。

1 个答案:

答案 0 :(得分:4)

放置这一行:

customer1.should_receive(:my_money)

expect(Bank.new.transfer(customer1, customer2, 2000)).to eq("Insufficient funds")

expect to have_receivedshould_receive具有不同的含义

如果对象已经收到预期的方法调用,则

expect to have_received通过 should_receive仅在对象将来(在当前测试用例范围内)接收到预期的方法调用时才会通过

如果你愿意写

expect(customer1).to receive(:my_money)

而不是

expect(customer1).to have_received(:my_money)

它也会失败。除非你把它放在调用这个方法的行之前。