我的课程如下
#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-expectations,expect
和should_receive
都相同,但expect
比should_receive
更具可读性。但为什么它失败了?提前谢谢。
答案 0 :(得分:4)
放置这一行:
customer1.should_receive(:my_money)
前
expect(Bank.new.transfer(customer1, customer2, 2000)).to eq("Insufficient funds")
expect to have_received
和should_receive
具有不同的含义
expect to have_received
通过
should_receive
仅在对象将来(在当前测试用例范围内)接收到预期的方法调用时才会通过
如果你愿意写
expect(customer1).to receive(:my_money)
而不是
expect(customer1).to have_received(:my_money)
它也会失败。除非你把它放在调用这个方法的行之前。