2010-07-01 47 views
3

Rails的关系和回调测试模型我还在学习RSpec的工作,所以我很抱歉,如果完全忽略了什么...在使用RSpec和Factory_Girl

我正在写一个测试的食谱有很多成分。这些成分实际上是以百分比形式添加的(配方中的总列数),所以我想确保在每次保存后总列更新。

所以现在我的RSpec的测试为recipe_ingredient模型是这样的:

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 

我只是呼吁刚才保存收据成分的快速更新的after_save的方法。这是非常直接的:

编辑:这update_percentage行动是在配方模型。我在保存原料后调用的方法只是查找它的配方,然后在其上调用此方法。

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

我搞砸了什么?运行测试时,我没有访问父对象的权限吗?我试图运行一个基本的方法来保存后更改父配方名称,但没有奏效。我确定这是我忽略的关系中的一些东西,但是所有的关系都是正确设置的。

感谢您的任何帮助/建议!

回答

2

update_attribute用于更新当前对象的属性。这意味着您需要在要更新属性的对象上调用update_attribute。在这种情况下,您想要更新配方,而不是配料。所以你必须拨打recipe.update_attribute(:total_percentage, ...)

此外,配料属于食谱,而不是其他成分。所以,而不是self.ingredients.sum(:percentage)你真的应该打电话recipe.ingredients.sum(:percentage)

另外,在测试它的total_percentage之前,您需要重新加载@recipe。即使它指向与@ingredient.recipe相同的数据库记录,它也不会指向内存中的同一个Ruby对象,因此更新为一个不会出现在另一个中。重新加载@recipe以在保存@ingredient后从数据库中获取最新值。

+0

对不起混淆update_percentage方法在配方模型中。 成分的after_save方法加载配方(@recipe = Recipe.find(self。),然后调用update_percentage(@ recipe.update_percentage) 如何在测试中重新加载配方? – sshefer 2010-07-01 21:06:20

+0

在测试中尝试过“@ recipe.reload”,它工作正常。谢谢伊恩,没有意识到我必须这样做! – sshefer 2010-07-01 21:16:00

2

顺便说一句,你可以在一个更清晰的方式建立自己的成分,因为你正在使用factory_girl已经:

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

这将建立和保存的成分。

+0

我不值得:)。我的代码感谢你。 – sshefer 2010-07-02 16:04:07

0

嘿,或者你在检查食谱中的total_percentage之前放了@ recipe.reload,或者使用expect。

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

期望是它的别名拉姆达{}应该,你可以在这里阅读更多关于它:rspec.rubyforge.org/rspec/1.3.0/classes/Spec/Matchers.html#M000168

相关问题