2012-03-14 64 views
0

我有一個名爲'transaction'的模型的日期屬性,當我保存它時,我想檢查它是否在一個範圍內,如果沒有,則將日期設置爲上一個事務。rspec stub out errors.add

它的工作,但我似乎無法讓我的測試工作,它添加錯誤時不斷爆炸。有沒有一種方法可以將'errors.add'這一行刪除,以便我可以隔離我的測試以檢查tran_date值是否已正確更改?

def tran_date_within_financial_year 
    range = ledger.fin_start..ledger.fin_end 
    unless range === tran_date 
     tran = Transaction.all.order("created_at").last 
     self.tran_date = tran.tran_date 
     errors.add(:tran_date, "is outside financial year") 
    end 
    end 

這裏是我的測試

context "date is empty" do 
    it "should set date to previous transaction" do 
    @prev_tran = Transaction.make!(:tran_date => Date.new(2012,02,03)) 
    @tran = Transaction.make!(:tran_date => "") 
    @tran.save 
    @tran.reload.tran_date.should eq(@prev_tran.tran_date) 
    end 
end 

當運行rspec的是結果:

1) Transaction Saving a transaction date is empty should set date to previous transaction 
    Failure/Error: @tran = Transaction.make!(:ledger => ledger, :tran_date => "") 
    ActiveRecord::RecordInvalid: 
     Validation failed: Tran date is outside financial year 

但是如果我註釋掉error.add功能,那麼我的測試通過。所以它正確地設置了前一個交易日期的值。問題在於錯誤.add一起停止測試。

回答

0

那麼,規範只是強調,你不能保存一個無效的對象。

而且該對象無效,因爲您向其添加錯誤。

這些規格應該通過:

context "date is empty" do 
    it "should set date to previous transaction" do 
    @prev_tran = Transaction.make!(:tran_date => Date.new(2012,02,03)) 
    @tran = Transaction.make(:tran_date => "") 
    @tran.should_not be_valid 
    @tran.errors.should have_key :tran_date 
    @tran.tran_date.should eq(@prev_tran.tran_date) 
    end 
end 
+0

通知你應該使用'make',不'make'已知無效的對象 – apneadiving 2012-03-14 22:35:00

+0

好像我忘了一些''上上面... :) – apneadiving 2012-03-14 23:11:52

+0

-1是!更好地解釋 – apneadiving 2014-11-18 14:55:30