【问题标题】:Testing Password Length with RSpec Using Devise使用 Devise 使用 RSpec 测试密码长度
【发布时间】:2013-04-29 12:38:00
【问题描述】:

我正在尝试测试我的用户模型(使用 devise gem)。我在devise gem 的rails4 分支上运行。我正在尝试编写最小密码长度的测试。

在我的user_spec.rb 中,我写道:

require 'spec_helper'

describe User do
  before { @user = User.new(full_name: "Example User", email: "user@example.com", password: "foobar", password_confirmation: "foobar") }

  subject { @user }

  it { should respond_to(:full_name) }
  it { should respond_to(:email) }
  it { should respond_to(:password) }
  it { should respond_to(:password_confirmation) }
  # it { should ensure_length_of(:password).is_at_least(8) }

  it { should be_valid }

  describe 'when full name is not present' do
    before { @user.full_name = " " }
    it { should_not be_valid }
  end

  describe 'when email is not present' do
    before { @user.email = " " }
    it { should_not be_valid }
  end

  describe 'when password is not present' do
    before {@user.password = " "}
    it { should_not be_valid }
  end

  describe 'when password is too short' do
    it { should ensure_length_of(:password).is_at_least(8) }
    it { should_not be_valid }
  end
end

但是,我在运行 rspec spec/ 时仍然遇到此故障/错误:

Failure/Error: it { should be_valid }
expected #<User id: nil, email: "user@example.com", encrypted_password:
"$2a$04$/Ifwb1dmfzG6xtBS/amRfOrTTopd8P6JSV48L0G/SWSh...",
reset_password_token: nil, reset_password_sent_at: nil,
remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil,
last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil,
created_at: nil, updated_at: nil, full_name: "Example User"> to be valid,
but got errors: Password is too short (minimum is 8 characters)
# ./spec/models/user_spec.rb:14:in `block (2 levels) in <top (required)>'

【问题讨论】:

  • foobar 长度为 6 个字符

标签: ruby-on-rails rspec devise ruby-on-rails-4


【解决方案1】:

在我看来,您的规范文件运行良好。

您的 it { should be_valid } 测试在第 14 行失败。这是失败的,因为您的密码为“foobar”,只有 6 个字符长,因此使用户无效。

尝试改变

before do  
  @user = User.new(
    full_name: "Example User", 
    email: "user@example.com", 
    password: "foobar", 
    password_confirmation: "foobar")
end

到:

before do  
  @user = User.new(
    full_name: "Example User", 
    email: "user@example.com", 
    password: "foobar123", 
    password_confirmation: "foobar123")
end

【讨论】:

    【解决方案2】:

    您为测试创建的用户没有有效密码。所以你的测试实际上保证了预期的行为。

    将您的测试用户密码更改为类似:“长测试密码”,它应该可以正常工作。

    最好的问候

    【讨论】:

      猜你喜欢
      • 2012-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-06
      • 1970-01-01
      • 1970-01-01
      • 2011-08-27
      • 2016-01-25
      相关资源
      最近更新 更多