使用FactoryGirl创建参数字符串以使用相关模型进行控制器测试 [英] Using FactoryGirl to create a parameter string for controller testing with related models

查看:73
本文介绍了使用FactoryGirl创建参数字符串以使用相关模型进行控制器测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我向模型添加了验证规则,以确保该记录在另一个模型中具有相关记录.很简单唯一的事情是,这破坏了我的控制器测试,在该测试中,我正在检查向该方法的发布是否会创建新记录:

I added a validation rule to a model which makes sure the record has a related record in another model. Pretty simple. Only thing is, this broke my controller test in which I'm checking that posting to the method creates a new record:

    it "should create a new recipe" do
      expect{
        post :create, recipe: FactoryGirl.build(:recipe).attributes
      }.to change(Recipe,:count).by(1)
    end

问题似乎是,工厂中的调用属性仅返回基本模型(配方)的属性,而不返回我在工厂中定义的相关模型的属性(如RecipeCategorization).当我这样调试时:

Problem seems to be, that calling attributes on the factory only returns attributes for the base model (recipe) and not for the related models (like RecipeCategorization) I've defined in the factory. When I debug it like this:

@recipe = FactoryGirl.build(:recipe)
@recipe.recipe_categorizations #this does contain the related data

是否可以在参数中也包含recipe_categorizations_attributes: []?

Is there a way to also include recipe_categorizations_attributes: [] in my parameters?

推荐答案

您对属性和关联的看法是正确的.您可以尝试以下方法:

You are right about the attributes and associations. You can try this:

post :create, recipe: FactoryGirl.build(:recipe).attributes.merge(association_id: @association.id)

或与您的关联相对应的类似内容

or something like that, that corresponds to your association

是否有一种方法也可以包含recipe_categorizations_attributes:[] 在我的参数中?

Is there a way to also include recipe_categorizations_attributes: [] in my parameters?

您的模型中是否有nested_attributes? 您也可以使用FactoryGirl(带有自己的工厂)来创建它们,并将它们与食谱的属性合并.

Do you have nested_attributes in your model? You can create those with FactoryGirl as well (with a factory of its own), and merge them with the attributes for recipe.

更新

这还将为您提供可使用的属性哈希:

This will also give you attributes hash that you can use:

@recipe.recipe_categorizations.attributes

这篇关于使用FactoryGirl创建参数字符串以使用相关模型进行控制器测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆