Building a json stub using FactoryGirl

谁说胖子不能爱 提交于 2019-12-07 09:51:30

问题


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.



来源:https://stackoverflow.com/questions/25205545/building-a-json-stub-using-factorygirl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!