我仍在努力学习 RSpec,所以如果完全忽略了某些东西,我很抱歉......
我正在为包含许多成分的食谱编写测试。成分实际上是按百分比添加的(配方中有一个总百分比列),所以我想确保每次保存后总列更新。
所以现在我对 recipe_ingredient 模型的 RSpec 测试是这样的:
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
我在搞砸什么吗?运行测试时我无权访问父对象吗?我尝试运行一种基本方法来在保存后更改父配方名称,但这没有用。我确定这是我忽略的关系中的某些东西,但所有关系都设置正确。
感谢您的任何帮助/建议!