2010-08-08 37 views
2

我有一個問題測試下面的模型accossioations:如何測試before_save方法,包括使用RSpec

class Bill < ActiveRecord::Base 
    belongs_to :consignee 
    before_save :calc_rate 

    def calc_rate 
    self.chargeableweight = self.consignee.destination.rate * self.weight 
    end 
end 

收貨人模型:

class Consignee < ActiveRecord::Base 
    belongs_to :destination 
    has_many :bills 
end 

這些控制器尚未觸及。

該應用程序的行爲是正確的(後續問題:該解決方案是否存在任何性能問題?) - 但測試中斷。

你有沒有對象,當你沒有 期待它!您可能預期了Array的一個 實例。在評估零發生錯誤 *

謝謝你的建議, 丹尼

更新:

該法案的測試中斷使用工廠女孩:

describe Bill do 

    it "should call the calc_rate method" do 
    bill = Factory.build(:bill) 
    bill.save! 
    bill.should_receive(:calc_rate) 
    end 
end 

你有一個當你沒有想到它的時候沒有對象!

工廠:

Factory.define :destination do |f| 
    f.airport_code "JFK" 
end 

Factory.define :consignee do |f| 
    ... 
    f.association :destination 
end 


Factory.define :bill do |f| 
    f.association :consignee 
    f.weight 10 
    f.chargeableweight 20.0 
    f.after_create do |bill| 
    bill.calc_rate 
end 
+0

粘貼您的測試案例... – Jagira 2010-08-08 11:20:28

回答

1
describe Consignee do 
    it "should calculate the rate" do 
    #pending 
    #make sure this spec is passing first, so you know your calc_rate method is fine. 
    end 

    it "should accept calc_rate before save" do 
    cosignee = mock("Consignee") 
    consignee.should_receive(:calc_rate).and_return(2) # => stubbing your value 
    end 
end 

我沒後臺了Rails應用程序來測試該代碼,但是這應該讓你關閉。另外,假設列chargeable_rate,重量等是模型上的列,你不需要自我調用。如果沒有實例方法或該名稱的變量可用,Ruby將隱式期待自己,它會自動查找類方法。

+0

感謝您的快速回答傑德。 對不起,不清楚。 我改變了問題 - 請參閱上面的 – 2010-08-08 12:29:02

+0

您的目標工廠正在等待方法速率,但這並未在您的目標工廠中定義。那至少有一個問題我看到。沒有一個堆棧跟蹤很難知道它在哪裏調用nil。 – 2010-08-08 12:44:38

+0

謝謝傑德,你是對的。 在工廠缺失率是問題... – 2010-08-08 17:18:27