2012-07-10 62 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')