user3084728
user3084728

Reputation: 605

FactoryGirl factory with Trait(s) that returns a Hash with stringed keys

I'm trying to use FactoryGirl to build a Hash that returns something like this:

 => {"3"=>"1", "6"=>"Word"}

I'm getting close but not 100% there yet...

The first factory definition i tried looked like this:

factory :faqtory, class: Hash do |f|
  f.ignore do
    fake_word Faker::Lorem.word
  end

  f.sequence(1.to_s) { |n| n }
  f.send(2.to_s,  fake_word.to_s.capitalize)

  initialize_with { attributes.stringify_keys }
end

Unfortunately this doesn't work:

1.9.3p448 :001 > FactoryGirl.build :faqtory
ArgumentError: Trait not registered: fake_word

After that didn't work i assumed the call to fake_word needed to be in a block but that makes no difference.

Any suggestions?

Upvotes: 2

Views: 1214

Answers (2)

Joe Ferris
Joe Ferris

Reputation: 2732

Ignored attributes are defined as methods that you can use from other attributes. When referring to them, you need to define the dependent attributes using a block:

factory :faqtory, class: Hash do |f|
  f.ignore do
    fake_word { Faker::Lorem.word }
  end

  f.sequence(1.to_s) { |n| n }
  f.send(2.to_s) { fake_word.to_s.capitalize }

  initialize_with { attributes.stringify_keys }
end

Defining an attribute without a block only works for literal values like 1 or "hello".

Update

As mentioned in the comments, you probably want fake_word to use a block as well.

Upvotes: 3

usha
usha

Reputation: 29359

Try this.

  factory :faqtory, class: Hash do |f|
    fake_word = Faker::Lorem.word

    f.sequence(1.to_s) { |n| n }
    f.send(2.to_s,  fake_word.to_s.capitalize)

    initialize_with { attributes.stringify_keys }
  end

Upvotes: 0

Related Questions