【问题标题】:Devise.friendly_token returns an equal hash all the timeDevise.friendly_token 始终返回一个相等的哈希值
【发布时间】:2013-08-18 23:39:53
【问题描述】:

我很困惑,试图了解这里发生了什么:
我在User 工厂中使用Devise.friendly_token

FactoryGirl.define do
  factory :user do
    email "user@example.com"
    password "secret"
    authentication_token Devise.friendly_token
  end
end

在一些测试中我使用工厂如下:

require 'spec_helper'

describe SessionsController do

  before do
    @user = User.gen!
    puts "Token = #{@user.authentication_token}" # <--- debugging output
  end

  describe "#create" do
    context "when sending ..." do
      it "renders a json hash ..." do
        api_sign_in @user
        expect(last_response.status).to eq(201)
      end
    end

    context "when sending ..." do
      it "renders a json hash ..." do
        user = User.gen!(email: "invalid@email.com")
        puts "Token2 = #{user.authentication_token}" # <--- debugging output
        api_sign_in user
        expect(last_response.status).to eq(422)
      end
    end
  end

  describe "#destroy" do
    context "when sending ..." do
      it "renders a json hash ..." do
        api_sign_out @user
        expect(last_response.status).to eq(200)
      end
    end
  end

end

调试输出显示令牌是每次调用的相同的哈希。 奇怪的!当我在控制台中测试Devise.friendly_token 时,它会在每次执行时生成一个随机哈希。这就是我对implementation 的期望。

我猜有一个主要的设计问题......请帮帮我。

【问题讨论】:

    标签: ruby-on-rails random devise auth-token http-token-authentication


    【解决方案1】:

    这一行:

    authentication_token Devise.friendly_token
    

    在工厂初始化时只调用一次Devise.friendly_token。你想要的

    authentication_token { Devise.friendly_token }
    

    每次FactoryGirl创建对象时都会评估块。

    【讨论】:

    • 再次感谢,它在规格中运行良好。当我在我的User 模型中使用Devise.friendly_token 时,为什么我不必这样做?
    • 我不确定你的意思。在User 模型中如何使用Devise.friendly_token
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-03
    相关资源
    最近更新 更多