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!
Factory Bot, originally known as Factory Girl, is a software library for the Ruby programming language that provides factory methods to create test fixtures for automated software testing.
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
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]" }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With