使用FactoryGirl为相关模型的控制器测试创建参数字符串

时间:2015-11-19 15:15:27

标签: ruby-on-rails factory-bot

我在模型中添加了验证规则,以确保记录在另一个模型中具有相关记录。很简单。唯一的问题是,这打破了我的控制器测试,其中我正在检查发布到该方法创建了一条新记录:

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

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

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

有没有办法在我的参数中加入recipe_categorizations_attributes: []

1 个答案:

答案 0 :(得分:1)

您对属性和关联是正确的。你可以试试这个:

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

或类似的东西,对应于您的关联

  

有没有办法还包括recipe_categorizations_attributes:[]   在我的参数?

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

更新

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

@recipe.recipe_categorizations.attributes