简体   繁体   English

使用RSpec测试密码长度验证

[英]Testing password length validation with RSpec

I'm writing some unit tests to ensure a User model cannot have a password < 8 characters long. 我正在编写一些单元测试,以确保用户模型的密码长度不超过8个字符。

I started with a User model: 我开始使用User模型:

class User < ActiveRecord::Base
  ...
  validates :password, :length =>{
    :minimum => 90,
    :too_short => "password is too short, must be at least %{count} characters"
  }, :on => :create

end

And a user_spec.rb test: 和user_spec.rb测试:

describe User do
  subject { FactoryGirl.build :user }

 its(:password) { should have_at_least(8).items }
end

However I realised that this doesn't actually test my validation, it just tests that my factory had a password >= 8 characters. 但是我意识到这实际上并没有测试我的验证,只是测试我的工厂有一个> = 8个字符的密码。

Is there a nice way to do this other than testing the valid? 除了测试有效之外,还有一种很好的方法吗? method for 0-7 character passwords? 0-7字符密码的方法?

My theory is that if I only test for 7 characters and someone accidentally hard codes that 4 characters passwords are OK this would pass validation but isn't really what was intended. 我的理论是,如果我只测试7个字符,并且有人意外硬编码4个字符密码就可以了,这将通过验证,但实际上不是预期的。 There could be some code else where that depends on a password being more than 8 characters (not likely but in other situations could be true) and so allowing a password of 4 is incorrect. 可能有一些代码,其中取决于密码超过8个字符(不太可能,但在其他情况下可能是真的),因此允许密码4是不正确的。

In this case the person who changed the password validation in the model won't know that that they've done anything wrong. 在这种情况下,在模型中更改密码验证的人不会知道他们做错了什么。

I'd just like to know how to properly test situations like this nicely with TDD. 我只想知道如何使用TDD正确测试这样的情况。

Using the ensure_length_of matcher in thoughtbot's shoulda matchers , you can do this: 在thinkbot的shoulda匹配器中使用ensure_length_of匹配 ,您可以这样做:

describe User do
  it { should validate_length_of(:password).is_at_least(8)
                                         .with_message(/password is too short/) }
end

See also: How can I test :inclusion validation in Rails using RSpec 另请参阅: 如何使用RSpec测试Rails中的包含验证

I don't know if this answers your question but I think you are safe with something like this: 我不知道这是否能回答你的问题,但我认为你这样做是安全的:

class User < ActiveRecord::Base
  validates :password, :length => {:minimum => 8 }
end

describe User do
  it "validates password length" do
    FactoryGirl.build(:user, password: "1234567").should_not be_valid
    FactoryGirl.build(:user, password: "12345678").should be_valid
  end
end

The reason is that for this test to let through a 4 character password somebody would have to have set a validation rule that says 4 characters is ok, 7 isn't ok, but 8 is ok. 原因是,为了让这个测试通过4个字符的密码,有人必须设置一个验证规则,说4个字符没问题,7个不正常,但8个没问题。 Not something that is likely to happen by accident. 不是偶然发生的事情。

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

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