设计测试过期的重置令牌

时间:2018-07-26 18:21:37

标签: ruby-on-rails devise factory-bot rspec-rails

我在这里需要一些帮助

我正在测试到期的reset_password_token应该更新还是不更新用户帐户。我正在将reset_password_sent_at模型中的User属性设置为过期值,但是无论如何用户密码都已更新。我正在使用Devise的可恢复模块。

factories / user.rb

factory :user_expired_unconfirmed_password do
  email { Faker::Internet.email }
  password { default_password }
  password_confirmation { default_password }
  confirmed_at { 2.days.ago }
  reset_password_token { nil }
  reset_password_sent_at { nil }
  updated_at { 2.hours.ago }
end

passwords_spec.rb

RSpec.describe Devise::PasswordsController, type: :request do
  it "creater users with expired reset_password_token (6 hours max.) shouldn't update password" do
    user = FactoryBot.create(:user_expired_unconfirmed_password)
    reset_password_token = user.send_reset_password_instructions

    old_passw = user.encrypted_password
    new_passw = 'test_new_passw_123'

    # expire token
    user.reset_password_sent_at = 7.hours.ago

    #### debbug ###
    # user.reload # if uncommented, got true in the below line
    puts user.reset_password_period_valid? # got false

    put user_password_path,
      :params => {
        "user" => {
          "reset_password_token" => reset_password_token,
          "password" => new_passw,
          "password_confirmation" => new_passw
        }
      }

    expect(user.reload.encrypted_password).to eq old_passw # got false here
  end
end

P.s:使用方法reset_password_period_valid?,如果我重新加载用户,则会得到falsetrue,但是独立于它没有传递断言。

有什么想法吗?我在模型测试中使用有效和到期reset_password_token来测试这些帮助程序方法,以更改密码,此密码可以正常使用。

1 个答案:

答案 0 :(得分:0)

尝试使用reset_password_token的新值保存用户

RSpec.describe Devise::PasswordsController, type: :request do
  it "creater users with expired reset_password_token (6 hours max.) shouldn't update password" do
    user = FactoryBot.create(:user_expired_unconfirmed_password)
    reset_password_token = user.send_reset_password_instructions

    # expire token
    user.reset_password_sent_at = 7.hours.ago
    user.save

    #### debbug ###
    user.reload
    puts user.reset_password_period_valid? # You should get false

    old_passw = user.encrypted_password
    new_passw = 'test_new_passw_123'

    put user_password_path,
      :params => {
        "user" => {
          "reset_password_token" => reset_password_token,
          "password" => new_passw,
          "password_confirmation" => new_passw
        }
      }

    expect(user.reload.encrypted_password).to eq old_passw # got false here
   end
end