Testing models with relationships and callbacks in Rails with RSpec and Factory_Girl

I'm still working on learning RSpec, so I'm sorry I completely missed something ...

I am writing a recipe test with many ingredients. The ingredients are actually added as a percentage (with the full column% in the wording), so I want to make sure that the total number of columns is updated after each save.

So now my RSpec test for the recipe_ingredient model has the following:

it "should update recipe total percent" do
  @recipe = Factory.create(:basic_recipe)

  @ingredient.attributes = @valid_attributes.except(:recipe_id)
  @ingredient.recipe_id = @recipe.id
  @ingredient.percentage = 20
  @ingredient.save!

  @recipe.total_percentage.should == 20
end

I have an after_save method that simply causes a quick update to the newly saved receipt instance. It is very simple:

EDIT: This update_percentage action is in the recipe model. The method that I call after saving the ingredient just looks at its recipe and then calls this method on it.

def update_percentage    
  self.update_attribute(:recipe.total_percentage, self.ingredients.calculate(:sum, :percentage))
end

- ? ? , , . , - , , .

/!

+3
3

update_attribute . , update_attribute , . , . recipe.update_attribute(:total_percentage, ...).

, , . self.ingredients.sum(:percentage) recipe.ingredients.sum(:percentage).

, @recipe total_percentage. , , @ingredient.recipe, Ruby , . @recipe, @ingredient.

+2

, , factory_girl:

@ingredient = Factory(:ingredient, :recipe => @recipe, :percentage => 20)

.

+2

, @recipe.reload total_percentage .

 it "should update recipe total percent" do
  @recipe = Factory.create(:basic_recipe)
  expect {
   @ingredient.attributes = @valid_attributes.except(:recipe_id)
   @ingredient.recipe_id = @recipe.id
   @ingredient.percentage = 20
   @ingredient.save!
  }.to change(@recipe,:total_percentage).to(20)
end

. rspec. http://www.slideshare.net/gsterndale/straight-up-rspec

expect is an alias for lambda {}. should and you can read about it here: rspec.rubyforge.org/rspec/1.3.0/classes/Spec/Matchers.html#M000168

0
source

Source: https://habr.com/ru/post/1752706/


All Articles