【问题标题】:ActiveRecord save in after_save callback not persisting during rspec test在 rspec 测试期间,在 after_save 回调中的 ActiveRecord 保存不会持续存在
【发布时间】: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


    【解决方案1】:

    在 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
    

    【讨论】:

      【解决方案2】:

      你需要stub回调动作:

      @blue_team.stub(:complete_game).and_return(true)
      

      【讨论】:

      • 您能否提供支持您声明的 rspec 文档的链接?
      猜你喜欢
      • 1970-01-01
      • 2015-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-24
      • 2011-07-11
      • 1970-01-01
      相关资源
      最近更新 更多