Building a json stub using FactoryGirl

2019-07-05 17:18发布

问题:

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.

回答1:

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


回答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.