为什么Rspec坚持密码属性为空,何时不是?

Mar*_*ark 2 ruby activerecord rspec ruby-on-rails

我正在编写一个用户模型,而RSpec坚持要求我将字段留空,实际上填充了一个完全有效的密码.这是我的spec/models/user_spec.rb文件:

require 'spec_helper'

describe User do
    before(:each) do
        @attr = {
            :name => "Example User",
            :email => "user@example.com",
            :password => "password",
            :password_confirmation => "password"
        }
    end

    it "should create a new instance given valid attributes" do
        User.create!(@attr)
    end

    it "should require a name" do
        no_name_user = User.new(@attr.merge(:name => ""))
        no_name_user.should_not be_valid
    end

    it "should reject names that are too long" do
        long_name = "a" * 51
        long_name_user = User.new(@attr.merge(:name => long_name))
        long_name_user.should_not be_valid
    end

    it "should accept valid email addresses" do
        addresses = %w[user@foo.com THE_USER@foo.bar.org first.last@foo.jp]
        addresses.each do |address|
            valid_email_user = User.new(@attr.merge(:email => address))
            valid_email_user.should be_valid
        end
    end

    it "should reject invalid email addresses" do
        addresses = %w[user@foo,com user_at_foo.org example.user@foo.]
        addresses.each do |address|
            invalid_email_user = User.new(@attr.merge(:email => address))
            invalid_email_user.should_not be_valid
        end
    end

    it "should reject duplicate email addresses" do
        User.create!(@attr)
        user_with_duplicate_email = User.new(@attr)
        user_with_duplicate_email.should_not be_valid
    end

    it "should reject email addresses identical up to case" do
        upcased_email = @attr[:email].upcase
        User.create!(@attr.merge(:email => upcased_email))
        user_with_duplicate_email = User.new(@attr)
        user_with_duplicate_email.should_not be_valid
    end

    describe "password validations" do
        it "should require a password" do
            User.new(@attr.merge(:password => "", :password_confirmation => "")).should_not be_valid
        end

        it "should require a matching password confirmation" do
            User.new(@attr.merge(:password_confirmation => "invalid")).should_not be_valid
        end

        it "should reject short passwords" do
            short = "a" * 5
            hash = @attr.merge(:password => short, :password_confirmation => short)
            User.new(hash).should_not be_valid
        end

        it "should reject long passwords" do
            long = "a" * 41
            hash = @attr.merge(:password => long, :password_confirmation => long)
            User.new(hash).should_not be_valid
        end
    end

    describe "password encryption" do
        before(:each) do
            @user = User.create!(@attr.merge(:password => "foobar", :password_confirmation => "foobar"))
        end

        it "should have an encrypted password attribute" do
            @user.should respond_to(:encrypted_password)
        end
    end
end
Run Code Online (Sandbox Code Playgroud)

这是我的app/models/user.rb文件:

class User < ActiveRecord::Base
    attr_accessible :name, :email
    attr_accessor :password

    email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

    validates(:name, :presence => true,
        :length => { :maximum => 50 })

    validates(:email, :presence => true,
        :format => { :with => email_regex },
        :uniqueness => { :case_sensitive => false })

    validates(:password, :presence => true,
        :confirmation => true,
        :length => { :within => 5..41 })
end
Run Code Online (Sandbox Code Playgroud)

运行RSpec后,我收到以下错误:

  1) User should create a new instance given valid attributes
     Failure/Error: User.create!(@attr)
     ActiveRecord::RecordInvalid:
       Validation failed: Password can't be blank
     # ./spec/models/user_spec.rb:25:in `block (2 levels) in <top (required)>'

  2) User should accept valid email addresses
     Failure/Error: valid_email_user.should be_valid
       expected #<User id: nil, name: "Example User", email: "user@foo.com", created_at: nil, updated_at: nil, encrypted_password: nil> to be valid, but got errors: Password can't be blank
     # ./spec/models/user_spec.rb:43:in `block (3 levels) in <top (required)>'
     # ./spec/models/user_spec.rb:41:in `each'
     # ./spec/models/user_spec.rb:41:in `block (2 levels) in <top (required)>'

  3) User should reject duplicate email addresses
     Failure/Error: User.create!(@attr)
     ActiveRecord::RecordInvalid:
       Validation failed: Password can't be blank
     # ./spec/models/user_spec.rb:56:in `block (2 levels) in <top (required)>'

  4) User should reject email addresses identical up to case
     Failure/Error: User.create!(@attr.merge(:email => upcased_email))
     ActiveRecord::RecordInvalid:
       Validation failed: Password can't be blank
     # ./spec/models/user_spec.rb:63:in `block (2 levels) in <top (required)>'

  5) User password encryption should have an encrypted password attribute
     Failure/Error: @user = User.create!(@attr.merge(:password => "foobar", :password_confirmation => "foobar"))
     ActiveRecord::RecordInvalid:
       Validation failed: Password can't be blank
 # ./spec/models/user_spec.rb:92:in `block (3 levels) in <top (required)>'
Run Code Online (Sandbox Code Playgroud)

每一个问题都是密码字段不是空白的!它填充了"密码"这个词 - 它在5和41的限制之间.在某些情况下,我已将它合并到该特定测试的属性中.

任何人都可以解释为什么这些测试失败了吗?

Jam*_*Lim 7

我不知道确切的问题,但我可以教你如何调试它.

步骤1:在测试环境中打开Rails控制台.

$> rails console test
Run Code Online (Sandbox Code Playgroud)

这允许您执行代码,就像它在测试规范中一样.我不确定你是否熟悉环境,但无论如何这里都是一篇好文章.

第2步:选择最简单的修复失败.在这种情况下,似乎是User should create a new instance given valid attributes.

步骤3:在测试控制台中逐行输入您希望针对失败规范执行的所有代码.

>> @attr = {
        :name => "Example User",
        :email => "user@example.com",
        :password => "password",
        :password_confirmation => "password"
    }
>> User.create!(@attr)
Run Code Online (Sandbox Code Playgroud)

第4步:如果您无法重现故障,则设置会出现其他问题.看看里面spec_helper.rb.也许你忘了跑rake db:migraterake db:test:prepare?当您使用Zeus等更高级的工具时,这一点变得更加重要.修理它.

第5步:如果你能够重现失败,是的!仔细检查打印的错误消息.正如@AmitKumarGupta所提到的那样,可能是因为password它不是可分配的.这是一篇关于这意味着什么的好文章.尝试各种创建方法user.例如,

>> user = User.new @attr
>> user.valid?  # should return true, but if it is false ...
>> user.errors  # is there an error for password and password confirmable?
>> user.inspect # maybe some rouge code deleted the password by accident?
Run Code Online (Sandbox Code Playgroud)

第6步:希望你现在找到了解决方案.添加解决方案并重新运行规范.现在重复步骤1直到全部通过.

边注

我强烈推荐FactoryGirlShoulda.这是应该有has_a_valid_factory的要点.

更新

如果您按照我上面的说明执行以下操作

>> u = User.new @attr
Run Code Online (Sandbox Code Playgroud)

您将看到以下错误消息:

WARNING: Can't mass-assign protected attributes for User: password, password_confirmation
Run Code Online (Sandbox Code Playgroud)

我上面链接的文章将解释这意味着什么.使用FactoryGirl将解决您的问题,或者您可以使用

user = User.new @attr # without password, password confirmation
user.password = 'password'
user.password_confirmation = 'password'
user.save!
Run Code Online (Sandbox Code Playgroud)