Using FactoryGirl to create a parameter string for

2019-08-10 14:19发布

问题:

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