Search code examples
rubyrspecfabrication-gem

Referencing a field in a Fabrication


In the below example I would like abbr to just be the first 3 letters of name but I get a >> undefined local variable name... I guess because name goes out of scope in the {} block?

Fabricator(:team) do
  name { Faker::Name.first_name }
  abbr { Faker::Name.first_name[0..2] }
  league { Fabricate(:league) }  
end

How can I make abbr just the first three letters of name?

i.e. this throws the error

Fabricator(:team) do
  name { Faker::Name.first_name }
  abbr { name[0..2] }  \\ error name is undefined here
  league { Fabricate(:league) }  
end

Solution

  • You can also do it by accepting the attributes hash in the abbr value block.

    Fabricator(:team) do
      name { Faker::Name.first_name }
      abbr { |attrs| attrs[:name][0..2] }
      league
    end
    

    Unrelated, but league will automatically expand to what you had specified above if you write it like this.