Testing password length validation with RSpec

岁酱吖の 提交于 2019-12-03 12:39:46
Chris Salzberg

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

See also: How can I test :inclusion validation in Rails using RSpec

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. Not something that is likely to happen by accident.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!