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

夙愿已清 提交于 2019-12-24 02:13:49

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/20645009/factorygirl-factory-with-traits-that-returns-a-hash-with-stringed-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!