代码之家  ›  专栏  ›  技术社区  ›  Lee McAlilly

Rails密码重置邮件程序测试未定义方法“html_safe”错误(使用Clearance gem)

  •  0
  • Lee McAlilly  · 技术社区  · 4 年前

    我试图在Rails中创建一个邮件程序测试,以检查密码重置邮件程序 Clearance sends .

    密码重置邮件程序的默认视图中有以下链接:

    <%= link_to "Change my password",
        edit_user_password_url(@user, token: @user.confirmation_token.html_safe) %>
    

    好像在打电话 html_safe 这是一件好事,但在我的邮件程序测试中,我一直收到这个错误:

    Minitest::UnexpectedError: ActionView::Template::Error: undefined method `html_safe' for nil:NilClass
    Did you mean?  html_safe?
    

    我不明白为什么会发生这种情况。这是我到目前为止的邮件测试:

    require "test_helper"
    
    class PasswordResetMailerTest < ActionMailer::TestCase
      setup do
        @user = users(:elvis)
      end
    
      test "password reset email" do
        email = ClearanceMailer.change_password(@user)
    
        # Send the email, then test that it got queued
        assert_emails 1 do
          email.deliver_now
        end
      end
    end
    

    为什么这会导致 undefined method html_safe 错误?

    0 回复  |  直到 4 年前
        1
  •  1
  •   Deepesh elements    4 年前

    你可以做的一件事来解决这个问题是:

    <%= link_to "Change my password",
    edit_user_password_url(@user, token: @user.confirmation_token&.html_safe) %>
    

    使用 &. 运算符,所以如果它是nil,那么它就不会抛出异常。异常的原因可能是直接调用邮件程序,因此在您的测试中您已经调用了 ClearanceMailer.change_password(@user) 当用户点击“忘记密码”或其他按钮(意味着在发送电子邮件之前有一个过程)时,会发送此电子邮件,该过程会在用户和电子邮件发送时设置确认令牌 @user.confirmation_token 存在。为了解决这个问题,你可以:

    1. 使用 &. 如上所述
    2. 调用在此之前调用的方法来设置确认令牌
    3. 或者,您可以手动设置随机确认令牌 user.update(confirmation_token: 'random text') 因为这只是一个测试,你正在检查电子邮件是否应该送达。