2012-07-10 41 views
0

在rspec中,我如何測試嚴格驗證失敗的屬性。我只能測試是否拋出了「ActiveModel :: StrictValidationFailed」異常。使用rspec在rails 3.2中測試嚴格驗證

這裏有一個例子:

it "should not be valid if the asset already exists" do 
    n = Factory.build(:private_attached_asset, :asset => Rack::Test::UploadedFile.new("test.pdf", 'application/pdf')) 
    expect { n.save }.should raise_error(ActiveModel::StrictValidationFailed) 
    #n.should have(1).error_on(:checksum) 
end 

註釋掉行再次拋出異常。

+0

此外,請考慮使用'「無效......」'而不是'「不應該是有效的......」'。 :) – grilix 2012-08-15 12:54:23

回答

1

您不能檢查嚴格驗證中的錯誤消息,因爲它們立即引發並且不設置errors對象。或者,您可以測試提出的確切錯誤消息:

expect { n.valid? }.to raise_error(ActiveModel::StrictValidationFailed, 'Exact message thrown') 
expect { n.valid? }.to raise_error(ActiveModel::StrictValidationFailed, 'Exact message thrown')