2010-08-10 26 views
3

我是一個完整的Ruby紐比和我使用RSpecrspec的預期引發「未定義的方法」

我測試類(帳戶)玩耍有這樣一行:

attr_reader :balance 

當我嘗試用這種方法測試:

it "should deposit twice" do 
    @acc.deposit(75) 
    expect { 
    @acc.deposit(50) 
    }.to change(Account.balance).to(125) 
end 

我得到這個錯誤:

NoMethodError in 'Account should deposit twice' 
undefined method `balance' for Account:Class 

我不明白爲什麼我得到的錯誤,因爲屬性'平衡'存在,但我可以看到,它不是一種方法,但不應該rspec能夠找到它嗎?

更新: 正如賈森指出,我應該@ acc.balance,因爲這是我所主張的。但是在做這件事時我得到'零不是一個符號'。

回答

4

它應該是@ acc.balance

it "should deposit twice" do 
    @acc = Account.new 
    @acc.deposit(75) 
    @acc.balance.should == 75 
    expect { 
    @acc.deposit(50) 
    }.to change(@acc, :balance).to(125) 
end 
+0

attr_reader位於Account類的實例上,而不是類本身。 – 2010-08-10 20:15:47

+0

改變了(這是我最初得到它的方式),現在我得到'零不是一個符號' – khebbie 2010-08-11 05:19:30

+0

我編輯了代碼,這現在對我來說很合適。 – 2010-08-11 13:22:31

1

我覺得應該是

expect {@acc.deposit(50)}.to change(@acc.balance}.to(125

1

它應該是:

it "should deposit twice" do 
    @acc.deposit(75) 
    expect { 
    @acc.deposit(50) 
    }.to change { @acc.balance }.to(125) 
end 

請注意,您需要使用花括號{ ... }而不是括號括號(...)大約在@acc.balance。否則@acc.balance在傳遞給change方法之前被評估,該方法需要符號或塊。

相關問題