什么是“验证逻辑”?我应该测试吗?
我正在使用 Ruby on Rails 3.0.9 和 RSpec 2。我想知道我应该测试什么“验证逻辑”。也就是说,如果在我的模型中我有:
class User < ActiveRecord::Base
validates :firstname
:presence => true
end
我应该测试以下内容?
- “应该有一个有效的名字”
- “不应该没有 有效的名字”
或者我应该测试两者?
I am using Ruby on Rails 3.0.9 and RSpec 2. I would like to know what "validation logic" I should test. That is, if in my model I have:
class User < ActiveRecord::Base
validates :firstname
:presence => true
end
What should I test of the following?
- "should have a valid first name"
- "should not have a valid first name"
Or should I test both?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以通过简单地执行以下操作来测试两者:
看看 应该为所有此类标准 Rails 验证提供匹配器。
You can test both by simply doing this:
Take a look at the shoulda matchers for all such standard Rails Validation.
我认为你不应该同时测试两者。这就足够了:
I think you should not test both. This will be enough:
基本上没有验证名称的算法,因为名称的形式非常以文化为中心。因此,实际上您应该避免对人名等内容进行复杂的验证。例如,有些地方/文化没有姓氏,因此即使验证他们的存在也是不合适的。还有一长串其他示例使验证名称成为一个非常糟糕的主意。有关验证名称本身问题的更多信息,请参阅我对此问题的回答< /a>.
话虽如此,一般来说,在验证任何字段时,我都会测试有效和无效数据。我确保,当我将字段设置为有效值时,
.valid?
方法返回true
,当它无效时,它返回false
。通常你不需要做一个长列表,你只需要测试
There is basically no algorithm for validating names, because the form of names is incredibly culture-centric. So, really you should avoid complex validations for something like a person's name. Some places/cultures don't have last names, for example, so even validating their presence isn't proper. There's a whole list of other examples that make validating names a really bad idea. For more information on the issue of validating names itself, see my answer to this question.
That being said, in general, when validating any field, I test both valid and invalid data. I make sure that, when I set a field to a valid value, that the
.valid?
method returnstrue
, and when it's invalid, that it returnsfalse
.Typically you don't need to do a long list, you just need to test
您还可以测试特定值:
you can also test for specific values: