- [ruby, rails, fabricator]

Tip: Fabricator 1.0 and memoization

Last night I faced a bug on my tests using Fabricator and decided to share it. It took some time to solve a problem using memoizations and Fabricator together.

Some context:

I got users on teams, and teams has many memberships. I wanted to cache the accepted members to improve performace. When I was testing, the cache always returned empty, even changing the name of variables or using diferent techniques to cache.

And I became suprised when I tested it the memoized code on console and it was running perfectly

The fabricator of user is something like that:

Fabricator(:user) do

  name { Faker::Name.name}

  email { |person| “#{person.name.parameterize}@example.com” }

  password “123”

   teams [Fabricate(:team)]

end

And the Fabricator of Team is:

Fabricator(:team) do

  name { Faker::Name.name }

end

The problem:

I was using the already created team by the fabricator relationship to create more memberships. But somehow, when I cached things, either using instance variables or ActiveSupport::Memoizeable I always got an empty {}.

So, after turning this:

@user = Fabricate(:user)

@second_user = Fabricate(:user, teams: [])

@team = @user.teams.first

@team.members « @second_user

to that:

@user = Fabricate(:user)

@second_user = Fabricate(:user, teams: [])

@team = @user.teams.create!({ name: “Teste”})

@team.members « @second_user

things worked like a charm on the tests.

(: