使用 FactoryGirl 创建参数字符串,用于控制器与相关模型的测试
Using FactoryGirl to create a parameter string for controller testing with related models
我向模型添加了验证规则,以确保该记录在另一个模型中具有相关记录。很简单。唯一的问题是,这破坏了我的控制器测试,我在其中检查发布到方法是否创建了新记录:
it "should create a new recipe" do
expect{
post :create, recipe: FactoryGirl.build(:recipe).attributes
}.to change(Recipe,:count).by(1)
end
问题似乎是,在工厂上调用属性仅 returns 基本模型(配方)的属性,而不是我在工厂中定义的相关模型(如 RecipeCategorization)的属性。当我这样调试时:
@recipe = FactoryGirl.build(:recipe)
@recipe.recipe_categorizations #this does contain the related data
有没有办法在我的参数中也包含 recipe_categorizations_attributes: []
?
关于属性和关联,你是对的。你可以试试这个:
post :create, recipe: FactoryGirl.build(:recipe).attributes.merge(association_id: @association.id)
或类似的东西,对应于您的协会
Is there a way to also include recipe_categorizations_attributes: []
in my parameters?
你的模型中有 nested_attributes 吗?
您也可以使用 FactoryGirl 创建它们(使用自己的工厂),并将它们与配方的属性合并。
更新
这还将为您提供可以使用的属性散列:
@recipe.recipe_categorizations.attributes
我向模型添加了验证规则,以确保该记录在另一个模型中具有相关记录。很简单。唯一的问题是,这破坏了我的控制器测试,我在其中检查发布到方法是否创建了新记录:
it "should create a new recipe" do
expect{
post :create, recipe: FactoryGirl.build(:recipe).attributes
}.to change(Recipe,:count).by(1)
end
问题似乎是,在工厂上调用属性仅 returns 基本模型(配方)的属性,而不是我在工厂中定义的相关模型(如 RecipeCategorization)的属性。当我这样调试时:
@recipe = FactoryGirl.build(:recipe)
@recipe.recipe_categorizations #this does contain the related data
有没有办法在我的参数中也包含 recipe_categorizations_attributes: []
?
关于属性和关联,你是对的。你可以试试这个:
post :create, recipe: FactoryGirl.build(:recipe).attributes.merge(association_id: @association.id)
或类似的东西,对应于您的协会
Is there a way to also include recipe_categorizations_attributes: [] in my parameters?
你的模型中有 nested_attributes 吗? 您也可以使用 FactoryGirl 创建它们(使用自己的工厂),并将它们与配方的属性合并。
更新
这还将为您提供可以使用的属性散列:
@recipe.recipe_categorizations.attributes