使用 RSpec 测试密码长度验证 [英] Testing password length validation with RSpec

查看:58
本文介绍了使用 RSpec 测试密码长度验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一些单元测试以确保用户模型不能有密码 <8 个字符长.

I'm writing some unit tests to ensure a User model cannot have a password < 8 characters long.

我从用户模型开始:

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

end

还有一个 user_spec.rb 测试:

And a user_spec.rb test:

describe User do
  subject { FactoryGirl.build :user }

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

但是我意识到这实际上并没有测试我的验证,它只是测试我的工厂有一个密码 >= 8 个字符.

However I realised that this doesn't actually test my validation, it just tests that my factory had a password >= 8 characters.

除了测试有效之外,还有其他好的方法可以做到这一点吗?0-7个字符密码的方法?

Is there a nice way to do this other than testing the valid? method for 0-7 character passwords?

我的理论是,如果我只测试 7 个字符并且有人不小心硬编码了 4 个字符的密码是可以的,这将通过验证,但并不是真正的意图.可能还有一些其他代码取决于密码超过 8 个字符(不太可能,但在其他情况下可能是正确的),因此允许密码为 4 是不正确的.

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. 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.

在这种情况下,更改模型中密码验证的人不会知道他们做错了什么.

In this case the person who changed the password validation in the model won't know that that they've done anything wrong.

我只想知道如何使用 TDD 正确地测试这种情况.

I'd just like to know how to properly test situations like this nicely with TDD.

推荐答案

使用 ensure_length_of 在thoughtbot 的应该匹配器,你可以这样做:

Using the ensure_length_of matcher in thoughtbot's shoulda matchers, you can do this:

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

另见:我如何测试:使用 RSpec 在 Rails 中进行包含验证

这篇关于使用 RSpec 测试密码长度验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆