Question

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 "user@example.com"
    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: "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

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top