简体   繁体   English

我应该测试什么“验证逻辑”?

[英]What “validation logic” should I test?

I am using Ruby on Rails 3.0.9 and RSpec 2. I would like to know what "validation logic" I should test. 我正在使用Ruby on Rails 3.0.9和RSpec2。我想知道应该测试什么“验证逻辑”。 That is, if in my model I have: 也就是说,如果在我的模型中我有:

class User < ActiveRecord::Base
  validates :firstname
    :presence => true
end

What should I test of the following? 我应该测试以下内容吗?

  1. "should have a valid first name" “应该一个有效的名字”
  2. "should not have a valid first name" “不应具有有效的名字”

Or should I test both? 还是我都应该测试?

You can test both by simply doing this: 您可以通过以下简单方法进行测试:

it "should validate presence of" do
   should validate_presence_of :firstname
end

Take a look at the shoulda matchers for all such standard Rails Validation. 查看所有此类标准Rails验证的Shoulda匹配器

I think you should not test both. 我认为您不应该同时测试两者。 This will be enough: 这样就足够了:

describe User do
  it { should validate_presence_of(:firstname) }
end

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? 当将字段设置为有效值时,我确保.valid? method returns true , and when it's invalid, that it returns false . 方法返回true ,无效时返回false

Typically you don't need to do a long list, you just need to test 通常,您不需要做长列表,只需要测试

  • A typical valid and invalid example 典型的有效和无效示例
  • A few edge cases 一些边缘情况

you can also test for specific values: 您还可以测试特定值:

describe User do    
    context "validations" do
        it { should_not allow_value("admin").for(:firstname) }
        it { should allow_value("JohnDoe").for(:firstname) }
    end    
end

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

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