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

时间:2013-07-14 02:26:31

标签: ruby-on-rails ruby activerecord rspec

我正在编写用户模型,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

这是我的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

运行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)>'

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

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

1 个答案:

答案 0 :(得分:7)

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

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

$> rails console test

这使您可以像执行测试规范一样执行代码。我不确定您是否熟悉环境,但无论如何这里都是good article

第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)

步骤4:如果您无法重现故障,则您的设置还有其他问题。查看spec_helper.rb内部。也许您忘了运行rake db:migraterake db:test:prepare?当您使用Zeus等更高级的工具时,这变得更加重要。解决它。

第5步:如果你能够重现失败,是的!仔细检查打印的错误消息。正如@AmitKumarGupta所提到的那样,可能是因为password不是可分配的。这是good article的含义。尝试各种方法来创建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?

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

旁注

我强烈推荐FactoryGirlShoulda。以下是should have_a_valid_factory的要点。

更新

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

>> u = User.new @attr

您将看到以下错误消息:

WARNING: Can't mass-assign protected attributes for User: password, password_confirmation

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

user = User.new @attr # without password, password confirmation
user.password = 'password'
user.password_confirmation = 'password'
user.save!