使用FactoryGirl构建json存根 [英] Building a json stub using FactoryGirl
问题描述
我试图使用工厂来构建json
,但是当我尝试build
时它是空的.
I am try to build a json
using a factory, but when i try to build
it's empty.
下面是Factory
类.
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);
但是我的hashed_response
似乎总是空的object
.
But my hashed_response
always seems to be empty object
.
推荐答案
使用FactoryGirl创建json就像使用航天飞机将菠萝去皮一样.尽力而为后,您将执行此操作,但这并不是为它创建航天飞机的目的.
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.
如果要在测试中重用此哈希结构,请将其存储在yaml文件中,并创建一些帮助程序方法以读取它(可以将其放置在spec/spec_helpers中).
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).
FactoryGirl正在使用method_missing
魔术来分配值.在您的代码中,您没有尝试执行任何方法,因为您只是在列出字符串,因此不会触发method_missing
魔术.
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.
为了完整起见,可以使用FG来做到这一点,但这不是很漂亮:
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
这篇关于使用FactoryGirl构建json存根的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!