我正在使用桌上足球测井应用程序。
我的模特遵循以下方案: 游戏 - >团队 - >位置 - >目标
在目标中我有一个after_save,它将检查两支球队是否进球10个。如果一个团队有,那么它设置一个胜利者(团队)并设置Game.completed_at。
此功能似乎通过用户测试在实践中拯救了胜利者和Game.completed_at,但是在我的Rspec测试中,在一个团队达到10个目标后,我看到在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设置了winner / completed_at,但在回调之外的&#39; TEST OUTPUT&#39;然后没有设置winner / completed_at。
rspec测试中的回调是否不会保留after_save回调中的更改?在生产中工作,似乎不会保存测试中的变化。
答案 0 :(得分:2)
收到以下回答,询问有关reddit.com/r/rails(http://www.reddit.com/r/rails/comments/2wlhrf/how_to_testing_before_save_callbacks/)的问题
在Team模型上执行回调后,需要相应对象的 .reload 。
测试按预期通过。
it "sets a winner after ten goals" do
10.times do
@blue_team.positions.first.goals.create
end
expect(@blue_team.reload.winner).to be true
end
答案 1 :(得分:0)
您需要stub
回调操作:
@blue_team.stub(:complete_game).and_return(true)