Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 828
user3084728 Avatar asked Dec 16 '13 21:12

user3084728


People also ask

What is Factory Girl in Ruby?

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.


2 Answers

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

like image 68
usha Avatar answered Sep 28 '22 02:09

usha


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]" }
like image 45
Nick Ellis Avatar answered Sep 28 '22 00:09

Nick Ellis