【问题标题】:password Ruby on Rails Tutorial by M. Hartl密码 Ruby on Rails 教程 M. Hartl
【发布时间】:2011-11-11 03:28:44
【问题描述】:

我刚刚开始使用 Rails,并决定遵循 M. Hartl 的“Ruby on Rails 教程”。似乎是一个很好的介绍。

我遇到了一个失败的测试,这让我发疯了。 我正在使用 rspec 2.7.0

运行 rails 3.1.1

我已经尝试修改条件,并且对“has_password”方法的测试有效。

失败的测试:

1)用户密码加密认证方法应该返回用户的电子邮件/密码匹配 失败/错误:matching_user.should == @user 预期的: # 得到:无(使用==) # ./spec/models/user_spec.rb:149:in `block (4 levels) in '

rspec 测试:

describe User do

before(:each) do
@attr = {:name => 'testing', 
         :email =>'testing@example.com',
         :password => "testtest",
         :password_confirmation => "testtest"}
end

...

describe "password encryption" do
  before(:each) do
    @user = User.create!(@attr)
  end

...

describe "authenticate method" do

  it "should exist" do
    User.should respond_to(:authenticate)
  end

  it "should return nil on email/password mismatch" do
    User.authenticate(@attr[:email], "wrongpass").should be_nil
  end

  it "should return nil for an email address with no user" do
    User.authenticate("bar@foo.com", @attr[:password]).should be_nil
  end

  it "should return the user on email/password match" do
    matching_user = User.authenticate(@attr[:email], @attr[:password])
    matching_user.should == @user
  end      
end

在用户模型中:

...

def has_password?(submitted_password) 
  encrypt_password == encrypt(submitted_password)
end

def self.authenticate(email, submitted_password)
  user = find_by_email(email) #self.where("email = ?", email) 
  return nil if user.nil?
  return user if user.has_password?(submitted_password)
end

private

 def encrypt_password
   self.salt = make_salt if new_record?
   self.encrypted_password = encrypt(password)
 end

我无法弄清楚我在这里做错了什么。

【问题讨论】:

标签: ruby-on-rails ruby ruby-on-rails-3.1


【解决方案1】:

在你失败的规范中,你有

matching_user.should == @user

但是@user 没有在任何地方定义,所以它被设置为 nil。

编辑:

尝试将以下 puts 添加到失败的规范中,并查看运行后在规范输出中得到什么结果。

it "should return the user on email/password match" do
  matching_user = User.authenticate(@attr[:email], @attr[:password])
  puts matching_user  # add this
  puts @user          # and also this
  matching_user.should == @user
end      

【讨论】:

  • 谢谢,但由于这篇文章的长度,我最初省略了创建用户的代码。我添加了它。还是一样的问题。
  • 谢谢!在您的调试帮助下,我发现我的 has_password 方法有一个错字:def has_password?(submitted_password) encrypted_password == encrypt(submitted_password) end
猜你喜欢
  • 1970-01-01
  • 2016-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多