How do I define a FactoryGirl factory that returns a Hash with stringed keys?
Asked Answered
J

2

7

I have this code:

FactoryGirl.define do
  factory :gimme_a_hash, class: Hash do
    one 'the number 1'
    two 'the number 2'
  end
end

It returns a hash that looks like:

1.9.3p448 :003 > FactoryGirl.build : gimme_a_hash
 => {:one=>"the number 1", :two=>"the number 2"}

How do I create a factory that returns a Hash with stringified numbers as keys?

Ideally i'd like to have the following hash returned:

 => { "1"=>"the number 1", "2"=>"the number 2"}

Thank you!

Jessie answered 16/12, 2013 at 21:44 Comment(0)
V
19

I am not sure if there is any other way. But this is one way of doing it

  factory :gimme_a_hash, class: Hash do |f|
    f.send(1.to_s, 'the number 1')
    f.send(2.to_s, 'the number 2')

    initialize_with {attributes.stringify_keys}
  end

Result:

1.9.3p194 :001 > FactoryGirl.build(:gimme_a_hash)
 => {"1"=>"the number 1", "2"=>"the number 2"}

Update

By default, factory_girl initializes the object of the given class and then calls the setter to set the values. In this case, a=Hash.new and then a.1 = 'the_number_1' which is not going to work

By saying initialize_with {attributes}, i am asking it to do Hash.new({"1" => "the number 1", "2" => "the number 2"})

Read the documentation for more info

Vrablik answered 16/12, 2013 at 22:26 Comment(2)
Could you please explain the initialize_with and it's block? I'd also love to understand how you came to the decision of using f.send.Jessie
Thank you. I posted a follow up Q with a different requirement set if you feel like taking a look. #20645509Jessie
L
1

You are looking for the attributes_for method.

factory :user do
  age { Kernel.rand(50) + 18 }
  email '[email protected]'
end

FactoryGirl.attributes_for(:user)
=> { :age => 31, :email => "[email protected]" }

FactoryGirl.attributes_for(:user).stringify_keys
=> { "age" => 31, "email" => "[email protected]" }
Lima answered 20/1, 2016 at 23:8 Comment(1)
I don't think he is looking for attributes_for. attributes_for implied you have have an Object rather than a data structure.Inducement

© 2022 - 2024 — McMap. All rights reserved.