2014-01-16 26 views
2

我上課像下面rspec的should_receive不工作,但想到的是工作

#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/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兩個 expectshould_receive是相同的,但 expectshould_receive更具可讀性。但爲什麼它失敗了?提前致謝。

回答

4

地方這條線:

customer1.should_receive(:my_money) 

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

expect to have_receivedshould_receive有diffent意義

expect to have_received通行證,如果對象已經收到了預期的方法調用,而 should_receive通過僅對象將將來接收預期的方法調用(在當前範圍內)牛逼測試用例)

如果你會寫的

expect(customer1).to receive(:my_money) 

代替

expect(customer1).to have_received(:my_money) 

它會失敗過。除非將它放在調用此方法的行之前。

+0

感謝它的工作。 –

相關問題