3

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
slindsey3000
  • 4,053
  • 5
  • 36
  • 56

2 Answers2

6

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.

Paul Elliott
  • 1,174
  • 8
  • 9
3

You should be able to do a before_save callback...

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

Edited to make optional if value for abbr is passed.

SteveTurczyn
  • 36,057
  • 6
  • 41
  • 53