Building a json stub using FactoryGirl

℡╲_俬逩灬. 提交于 2019-12-05 17:43:04

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

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.

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