Devise.friendly_token returns an equal hash all the time

2.8k views Asked by At

I am all mixed up trying to understand what happens here:
I use Devise.friendly_token in a User factory.

FactoryGirl.define do
  factory :user do
    email "[email protected]"
    password "secret"
    authentication_token Devise.friendly_token
  end
end

In some tests I use the factory as follows:

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: "[email protected]")
        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

The debugging output shows that the token is the same hash on every call. Strange! When I test Devise.friendly_token in the console it generates a random hash on every execution. That's what I expect looking at the implementation.

I guess there is a major design problem ... Please help me out.

1

There are 1 answers

2
Sergej Koščejev On BEST ANSWER

This line:

authentication_token Devise.friendly_token

will call Devise.friendly_token only once when the factory is initialized. You want

authentication_token { Devise.friendly_token }

which will evaluate the block every time an object is created by FactoryGirl.