当我知道正在调用该方法时,RSpec测试未通过

wj8zmpe1  于 2022-09-21  发布在  Ruby
关注(0)|答案(1)|浏览(174)

我有以下课程:

class UserRewards
  def self.grant(reward_id:, submission_id:, user_id:)
    debugger
    ActiveRecord::Base.transaction do
      puts 'ActiveRecord::Base.transaction'
    end
  end
end

以及以下测试:

require 'rails_helper'

RSpec.describe UserRewards do
  describe '.grant' do
    it 'grants a reward to a user' do
      user = build_stubbed(:user)
      submission = build_stubbed(:submission)
      reward = build_stubbed(:reward)

      UserRewards.grant(
        reward_id: reward.id,
        submission_id: submission.id,
        user_id: user.id,
      )

      expect(ActiveRecord::Base).to receive(:transaction)
    end
  end
end

当我运行测试时,我只是想验证ActiveRecord::Base是否收到了:transaction,但无论我做什么,或者如何尝试重新构造此测试,我总是收到以下失败:

1) UserRewards.grant grants a reward to a user
    Failure/Error: expect(ActiveRecord::Base).to receive(:transaction)

      (ActiveRecord::Base (class)).transaction(*(any args))
          expected: 1 time with any arguments
          received: 0 times with any arguments

我已经验证了该方法正在通过调试器运行:

(rdbg) n    # next command
[1, 10] in ~/workspace/my-app/lib/services/user_rewards.rb
     1| class UserRewards
     2|   def self.grant(reward_id:, submission_id:, user_id:)
     3|     debugger
     4|     ActiveRecord::Base.transaction do
=>   5|       puts 'ActiveRecord::Base.transaction'
     6|     end
     7|   end
     8|
     9|   def self.revoke(reward_id:, submission_id:, user_id:)
=>#0    block in grant at ~/workspace/my-app/lib/services/user_rewards.rb:6

# 1  block in within_new_transaction at ~/.rbenv/versions/3.0.3/lib/ruby/gems/3.0.0/gems/activerecord-7.0.1/lib/active_record/connection_adapters/abstract/transaction.rb:319

# and 74 frames (use `bt' command for all frames)

我知道我一定是做错了什么。我不必在ActiveRecord::Base上存根该方法,对吗?

bkkx9g8r

bkkx9g8r1#

如果您只需要知道某个事务已被调用,则可以存根此方法,然后检查它是否已被调用。你的it很胖,最好用AAA-原理

require 'rails_helper'

describe UserRewards do
  describe '.grant' do
    let(:user) { build_stubbed(:user) }
    let(:submission) { build_stubbed(:submission) }
    let(:reward) { build_stubbed(:reward) }

    before do
      allow(ActiveRecord::Base).to receive(:transaction)

      described_class.grant(
        reward_id: reward.id,
        submission_id: submission.id,
        user_id: user.id,
      )
    end

    it 'calls database transaction' do
      expect(ActiveRecord::Base).to have_received(:transaction).once
    end
  end
end

相关问题