简体   繁体   English

测试Rails模型验证

[英]Testing Rails model validations

There's many examples of testing RoR model validations. 有许多测试RoR模型验证的例子。 Even keeping the test being DRY across multiple models. 甚至在多个模型中保持测试干燥。 But isn't it testing Rails which is already tested? 但它不是测试已经测试过的Rails吗?

@user = User.make
@user.name = nil

@user.should_not be_valid

Isn't it testing if Rails validations work? 是不是测试Rails验证是否有效?

Isn't it testing if Rails validations work? 是不是测试Rails验证是否有效?

The point is that it tests that your model validates the presence of name. 关键是它测试您的模型验证名称的存在。 The fact that it also in effect tests that the Rails validation works, that Rspec works, that Ruby works, that your OS works, and that the rules of physics haven't suddenly changed, is beside the point. 事实上,它实际上测试了Rails验证的工作原理,Rspec的工作原理,Ruby的工作原理,操作系统的工作原理以及物理规则没有突然改变,这一点也不重要。

The point is that you test that your model is using the validation. 关键是您测试模型是否正在使用验证。 I agree with you, though, that your example tests the validation itself, and the test is also somewhat ambiguous. 不过,我同意你的看法,你的例子测试验证本身,测试也有些含糊不清。

If you are using the shoulda gem, you can simply use should validate_presence_of(:name) . 如果您使用的是shoulda gem,则可以使用should validate_presence_of(:name)

Think of a method in your program where you have called update_attribute (update_attribute skips validation). 想一想您的程序中调用update_attribute(update_attribute跳过验证)的方法。 Calling that method leaves the object in an invalid state, however the database still gets updated. 调用该方法会使对象处于无效状态,但数据库仍会更新。 Using valid?/invalid? 使用有效?/无效? can help you catch such cases. 可以帮助你抓住这种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM