2017-09-04 44 views
0

使用模型制定者時,我有與線訂單模型計算的產品總總價用戶訂購早該-匹配錯誤之前validarion

before_validation :set_total! 
validates :total, presence: true, numericality: { greater_than_or_equal_to: 0 } 

set_total看起來像這樣

def set_total! 
    self.total = products.map(&price).sum 
end 

在我的規格我想檢查驗證總額實現TDD

it { should validate_presence_of(:total) } 
it { should validate_numericality_of(:total).is_greater_than_or_equal_to(0) } 

不幸的是我收到以下錯誤

Failure/Error: it { should validate_presence_of(:total) }

Order did not properly validate that :total cannot be empty/falsy. 
    After setting :total to ‹nil› -- which was read back as 
    ‹#<BigDecimal:5634b8b81008,'0.0',9(27)>› -- the matcher expected the 
    Order to be invalid, but it was valid instead. 

    As indicated in the message above, :total seems to be changing certain 
    values as they are set, and this could have something to do with why 
    this test is failing. If you've overridden the writer method for this 
    attribute, then you may need to change it to make this test pass, or 
    do something else entirely. 

我該如何解決這個問題?

回答

1

使用validate_presence_of匹配大致相當於手工編寫這個測試:

describe Order do 
    it "fails validation when total is nil" do 
    order = Order.new 
    order.total = nil 
    order.validate 
    expect(order.errors[:total]).to include("can't be blank") 
    order.total = 42 
    expect(order.errors[:total]).not_to include("can't be blank") 
    end 
end 

如果要運行這個測試,你會發現,這將失敗。爲什麼?因爲在您的模型中,當執行驗證時,您將total設置爲非零值。這就是你得到這個錯誤的原因。

所以你不需要驗證或匹配器,因爲沒有人會失敗。