【发布时间】:2012-01-21 16:33:12
【问题描述】:
RSpec 新手在这里。
我正在尝试测试我的模型,这些模型具有使用 update_attributes 更新其他模型值的方法。
我确定这些值已保存在数据库中,但它们没有通过规范。
但是,当我包含 @user.reload 之类的内容时,它会起作用。
我想知道我是否做错了事。具体来说,一个模型应该如何测试改变其他模型属性的模型?
已更新代码:
describe Practice do
before(:each) do
@user = build(:user)
@user.stub!(:after_create)
@user.save!
company = create(:acme)
course = build(:acme_company, :company => company)
course.save!
@practice = create(:practice, :user_id => @user.id, :topic => "Factors and Multiples" )
end
describe "#marking_completed" do
it "should calculate the points once the hard practice is done" do
@practice.question_id = Question.find(:first, conditions: { diff: "2" }).id.to_s
@practice.responses << Response.create!(:question_id => @practice.question_id, :marked_results => [true,true,true,true])
@practice.save!
lambda {
@practice.marking_completed
@practice.reload # <-- Must add this, otherwise the code doesn't work
}.should change { @practice.user.points }.by(20)
end
end
结束
实践.rb
def marking_completed
# Update user points
user.add_points(100)
self.completed = true
self.save!
结束
在 User.rb 中
def add_points(points)
self.points += points
update_attributes(:points => self.points)
结束
【问题讨论】:
-
您有任何可以发布的代码和测试示例吗?
-
我已经更新了代码,请看一下!谢谢
标签: ruby-on-rails-3.1 rspec2 rspec-rails