Using FactoryGirl to create a parameter string for controller testing with related models

試著忘記壹切 提交于 2019-12-11 11:47:47

问题


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

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

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


回答1:


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

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

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.


UPDATE

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

@recipe.recipe_categorizations.attributes


来源:https://stackoverflow.com/questions/33807690/using-factorygirl-to-create-a-parameter-string-for-controller-testing-with-relat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!