gpt4 book ai didi

ruby-on-rails-3 - 工厂女孩 : why does attributes_for omit some attributes?

转载 作者:行者123 更新时间:2023-12-03 14:42:30 26 4
gpt4 key购买 nike

我想在 Controller 测试中使用 FactoryGirl.attributes_for,如下所示:

it "raise error creating a new PremiseGroup for this user" do
expect {
post :create, {:premise_group => FactoryGirl.attributes_for(:premise_group)}
}.to raise_error(CanCan::AccessDenied)
end

...但这不起作用,因为 #attributes_for 省略了 :user_id 属性。这是 #create之间的区别和 #attributes_for :
>> FactoryGirl.create(:premise_group)
=> #<PremiseGroup id: 3, name: "PremiseGroup_4", user_id: 6, is_visible: false, is_open: false)
>> FactoryGirl.attributes_for(:premise_group)
=> {:name=>"PremiseGroup_5", :is_visible=>false, :is_open=>false}

请注意, #attributes_for 中没有 :user_id .这是预期的行为吗?

FWIW,我的工厂文件包含 :premise_group 的定义和 :user :
FactoryGirl.define do
...
factory :premise_group do
sequence(:name) {|n| "PremiseGroup_#{n}"}
user
is_visible false
is_open false
end
factory :user do
...
end
end

最佳答案

简答:

按照设计,FactoryGirl 的 attribues_for故意省略会触发数据库事务的事情,因此测试将运行得很快。但是你可以写一个build_attributes方法(如下)对所有属性进行建模,如果您愿意花时间的话。

原答案

深入研究 FactoryGirl 文档,例如this wiki page ,你会发现提到 attributes_for忽略关联 - 请参阅下面的更新。作为一种解决方法,我在 FactoryGirl.build(...).attributes 周围封装了一个辅助方法。条id , created_at , 和 updated_at :

def build_attributes(*args)
FactoryGirl.build(*args).attributes.delete_if do |k, v|
["id", "created_at", "updated_at"].member?(k)
end
end

所以现在:
>> build_attributes(:premise_group)
=> {"name"=>"PremiseGroup_21", "user_id"=>29, "is_visible"=>false, "is_open"=>false}

......这正是预期的结果。

更新

吸收了 FactoryGirl 创作者的评论,我明白为什么 attributes_for忽略关联:引用关联会生成对数据库的调用,这在某些情况下会大大减慢测试速度。但如果你需要关联, build_attributes上面显示的方法应该有效。

关于ruby-on-rails-3 - 工厂女孩 : why does attributes_for omit some attributes?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10290286/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com