Rails测试 – 如何测试特定的validation?

使用默认的Rails测试套件,我如何编写仅测试某些validation的测试? 例如,如果我有presence,numeric和我自己的validation器的validation,我该如何测试数字?

假设我没有数字validation工作,所以此测试应该失败:

test "should test numeric validator" do post = Post.new(:number => 'not a number') assert !post.save, "it saved a non-numeric value for :number" end 

但它会通过,因为我自己的validation器不允许它出于其他原因保存,所以我的测试没有真正测试。

你可以断言特定字段的post.errors哈希,即:

 assert_nil post.errors[:number], "it saved a non numeric value for :number"