0

在运行 rails 测试时,我遇到了 RSpec 的一些问题。测试如下:

it "allows a user to request a password reset" do
  user = FactoryGirl.create(:user, :name => "John Smith", :email => "john@test.org")
  identity = Identity.create!(email: user.email, password: "please", password_confirmation: "please")
  visit "/"
  click_on "Forgotten password?"
  fill_in "email", :with => "john@test.org"
  click_on "Reset Password"
  ActionMailer::Base.deliveries.last.to.should include(user.email)
  ActionMailer::Base.deliveries.last.body.should include(identity.password_reset_token)
  visit '/password_resets/' + identity.password_reset_token.to_s + '/edit'

    ^ **** ERROR HERE : password_reset_token is nil! ****

  fill_in "identity_password", :with => "newpass123"
  fill_in "identity_password_confirmation", :with => "newpass123"
  click_on "Update Password"
  within page.all('div#loginModal')[0] do
    fill_in "auth_key", :with => "john@test.org"
    fill_in "password", :with => "newpass123"
    click_button "Log in"
  end
  page.should have_content("Hi John")
end

你可以看到我已经概述了我要返回的错误,这很奇怪,因为当我检查发送的电子邮件时,它实际上会生成一个 password_reset_token。

有关信息,我用来执行此操作的代码是:

class PasswordResetsController < ApplicationController

  def create
    identity = Identity.find_by_email(params[:email])
    identity.send_password_reset if identity
    redirect_to root_url, :notice => "Email sent with password reset instructions."
  end

  def edit
    @identity = Identity.find_by_password_reset_token!(params[:id])
  end

  def update
    @identity = Identity.find_by_password_reset_token!(params[:id])
    if @identity.password_reset_sent_at < 2.hours.ago
      redirect_to new_password_reset_path, :alert => "Password reset has expired."
    elsif @identity.update_attributes(params[:identity])
      redirect_to root_url, :notice => "Password has been reset."
    else
      render :edit
    end
  end

end

和...

class Identity < OmniAuth::Identity::Models::ActiveRecord
  attr_accessible :email, :password, :password_confirmation

  validates_uniqueness_of :email
  validates_format_of :email, :with => /^[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$/i

  def send_password_reset
    generate_token(:password_reset_token)
    self.password_reset_sent_at = Time.zone.now
    self.save!
    UserMailer.password_reset(self).deliver
  end

  private

    def generate_token(column)
      begin
        self[column] = SecureRandom.urlsafe_base64
      end while Identity.exists?(column => self[column])
    end
end

谁能建议为什么会发生这种情况?这与我的测试环境中某处未保存/访问或缓存的数据库记录有关吗?

任何帮助表示赞赏。

4

2 回答 2

1

只是一个猜测:你不需要更新你的身份变量,比如通过电子邮件找到它,以便用新参数更新对象吗?在访问“password_resets”之前,请尝试使用

Identity.find_by_email(user.email)

于 2013-01-22T14:51:23.987 回答
0

您可能会遇到时间问题。完成该click_on 'Reset Password'步骤后,检查页面是否返回预期值,然后再继续执行该visit 'passwords_reset...'步骤。

于 2013-01-23T05:23:34.537 回答