我正在编写一些单元测试,以确保用户模型的密码长度不能小于 8 个字符。
我从用户模型开始:
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 测试:
describe User do
subject { FactoryGirl.build :user }
its(:password) { should have_at_least(8).items }
end
然而我意识到这实际上并没有测试我的验证,它只是测试我的工厂的密码 >= 8 个字符。
除了测试有效性之外,还有其他好方法吗? 0-7个字符的密码的方法?
我的理论是,如果我只测试 7 个字符,而有人意外地对 4 个字符的密码进行了硬编码,那么这将通过验证,但并不是真正的意图。
可能还有一些代码依赖于密码超过 8 个字符(不太可能,但在其他情况下可能是这样),因此允许 4 个密码是不正确的。
在这种情况下,在模型中更改密码验证的人不会知道他们做错了什么。
我只是想知道如何使用 TDD 很好地正确测试这样的情况。
使用确保长度 https://github.com/thoughtbot/shoulda-matchers/blob/v1.2.0/lib/shoulda/matchers/active_model/ensure_length_of_matcher.rbThoughtbot 中的匹配器应该匹配者 https://github.com/thoughtbot/shoulda-matchers, 你可以这样做:
describe User do
it { should validate_length_of(:password).is_at_least(8)
.with_message(/password is too short/) }
end
也可以看看:如何使用 RSpec 测试 Rails 中的包含验证 https://stackoverflow.com/questions/7415660/how-can-i-test-inclusion-validation-in-rails-3-using-rspec
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)