如何使用rspec测试私有方法的调用

时间:2019-02-05 16:29:50

标签: ruby-on-rails-4 rspec

我正在尝试确保给定方法在被回调调用时被调用。 基本上,我有一个RiskMatrix模型,该模型在回调after_save上调用2个私有方法 因此,我正在尝试测试这些方法是否正确调用。

非常感谢您的帮助

class RiskMatrix < ActiveRecord::Base
   after_save :alert_admin, :save_suspicious_ip, if: proc {score.length >= ALERT_THRESHOLD}

    private
    def alert_admin
        [...]
    end

    def save_suspicious_ip
        [...]
    end
end

risk_matrix_spec.rb

 describe 'after_save' do
  context 'score.length > ALERT_THRESHOLD' do
    it 'should run alert_admin' do
      matrix = build(:risk_matrix, score: 'ABCD')
      expect(matrix).to receive(:alert_admin)
    end

    it 'should run save_suspicious_ip' do
      matrix = create(:risk_matrix, score: 'ABCD')
      expect(matrix).to receive(:save_suspicious_ip)
    end

  end
end

两项测试均失败

 (#<RiskMatrix id: 3201, score: "ABCD", user_id: 3115, created_at: "2019-02-05 16:27:01", updated_at: "2019-02-05 16:27:01">).alert_admin(*(any args))
    expected: 1 time with any arguments
    received: 0 times with any arguments

    (#<RiskMatrix id: nil, score: "ABCD", user_id: nil, created_at: nil, updated_at: nil>).save_suspicious_ip(*(any args))
    expected: 1 time with any arguments
    received: 0 times with any arguments

2 个答案:

答案 0 :(得分:2)

您可以使用shoulda-callback-matchers来测试您的回调

it { is_expected.to callback(:alert_admin).after(:save) }

另一种测试方法是验证保存矩阵后必须存在suspicious_ip。

let(:matrix) { create(:risk_matrix, score: 'ABCD') }
context "when score.length > ALERT_THRESHOLD" do
  it "after create a matrix" do
   expect(matrix.suspicious_ip).to_not be_nil
  end
end
context "when score.length < ALERT_THRESHOLD" do
  it "after create a matrix" do
   expect(matrix.suspicious_ip).to be_nil
  end
end

答案 1 :(得分:0)

也许我遗漏了一些东西,但是您却没有看到保存呼叫,

it 'should run alert_admin' do
  matrix = build(:risk_matrix, score: 'ABCD')
  allow(matrix).to receive(:alert_admin)
  matrix.save!
  expect(matrix).to have_received(:alert_admin).once
end

在保存之前,请让RSpec知道要对该方法进行存根,在保存之后,请确认该方法已被调用。