Building a json stub using FactoryGirl
Asked Answered
K

2

8

I am try to build a json using a factory, but when i try to build it's empty.

Below is Factory class.

require 'faker'

FactoryGirl.define do 
    factory :account do |f|
        f.name {Faker::Name.name}
        f.description {Faker::Name.description}     
    end

    factory :accjson, class:Hash do
        "@type" "accountResource"
        "createdAt" "2014-08-07T14:31:58"
        "createdBy" "2"        
        "disabled"  "false"        
    end 
end

Below is how i am trying to build.

hashed_response = FactoryGirl.build(:accjson)        
expect(account.to_json).to eq(hashed_response.to_json);

But my hashed_response always seems to be empty object.

Kadi answered 8/8, 2014 at 14:12 Comment(0)
P
7

Using FactoryGirl to create a json is like using space shuttle to peel the pineapple. You'll do that after you try hard enough, but it is not what shuttle has been created for.

If you are reusing this hash structure in your test, store it within yaml file and create some helper methods to read it (you can place them within spec/spec_helpers).

Reason why your code doesn't work:

FactoryGirl is using method_missing magic to assign values. In your code, you are not trying to execute any methods, as you are just listing strings, so the method_missing magic is not triggered.

Way to do this with FactoryGirl (read the top paragraph!):

For completeness, there is a way to do this with FG, however is not very pretty:

factory :accjson, class: OpenStruct do
  send :'@type', "accountResource"
  createdAt "2014-08-07T14:31:58"
  createdBy "2"        
  disabled  "false"        
end

hashed_response = FactoryGirl.build(:accjson).marshal_dump.to_json
Paisley answered 8/8, 2014 at 14:29 Comment(4)
pastie.org/9455888 why is the API response different from the stub which i am creating.Kadi
@Kadi - How did you got those values. One is escaped, the other one is not.Paisley
First one is the json stub created via Factorygirl and other one is my API response.Kadi
I disagree with this philosophy, especially since Activerecord is less used. This means, for instance, if you used MongoId you would not be able to use fixtures and would have to use FactoryGirl for a simple json.Condescendence
V
2

I have implemented this using the hashie gem.

My factories then look like this:

FactoryGirl.define do
  factory :some_factory_name, class: Hashie::Mash do
    skip_create
    attribute1 { value }
    attribute2 { "test" }
    sequence(:attribute3) { |n| "AttributeValue#{n}" }
  end
end

This has worked well for me as it behaves almost exactly like a Hash but with the convenience of a factory and the simplicity of getting and setting attributes on a Struct.

Vanda answered 20/4, 2017 at 10:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.