【发布时间】:2015-04-22 14:38:26
【问题描述】:
我正在开发一个桌上足球记录应用程序。
我的模型遵循以下方案: 比赛 -> 球队 -> 位置 -> 进球
在 Goal 中,我有一个 after_save,它将检查任何一支球队是否进了 10 个球。如果一个团队有,那么它设置一个获胜者(团队)并设置 Game.completed_at。
此功能似乎通过用户测试在实践中保存了获胜者和 Game.completed_at,但在团队达到 10 个目标后的我的 Rspec 测试中,我看到在 Goal 中调用了 after_save 回调,但在测试中的回调之后它为如果没有保存这些列。我不确定发生了什么。
class Goal < ActiveRecord::Base
after_save :complete_game
def complete_game
game = self.position.team.game
isGameComplete = false
game.teams.each do |team|
if team.get_goals_total == 10
team.winner = true
team.save!
puts "complete_game: team.winner: #{team.winner}"
game.completed_at = DateTime.now
game.save!
isGameComplete = true
end
end
puts "complete_game: game.completed_at: #{game.completed_at}"
end
Rspec 测试:
it "sets a winner after ten goals" do
@blue_team.positions.first.goals.create
@blue_team.positions.first.goals.create
@blue_team.positions.first.goals.create
@blue_team.positions.first.goals.create
@blue_team.positions.first.goals.create
@blue_team.positions.first.goals.create
@blue_team.positions.first.goals.create
@blue_team.positions.first.goals.create
@blue_team.positions.first.goals.create
@blue_team.positions.first.goals.create
puts "winner: #{@blue_team.winner}"
puts "completed_at: '#{@game.completed_at}'"
expect(@blue_team.winner).to be true
end
Rspec 输出:
complete_game: game.completed_at:
complete_game: game.completed_at:
complete_game: game.completed_at:
complete_game: game.completed_at:
complete_game: game.completed_at:
complete_game: game.completed_at:
complete_game: game.completed_at:
complete_game: game.completed_at:
complete_game: game.completed_at:
complete_game: team.winner: true
complete_game: game.completed_at: 02/20/2015 12:44 PM
TEST OUTPUT: winner: false
TEST OUTPUT: completed_at: ''
sets a winner after ten goals (FAILED - 1)
查看日志,after_save 设置了获胜者/完成_at,但在“测试输出”中的回调之外,未设置获胜者/完成_at。
rspec 测试中的回调不会保留在 after_save 回调中所做的更改吗?在生产中工作,似乎没有保存测试中的更改。
【问题讨论】:
标签: ruby-on-rails rspec