【问题标题】:How to test that private method is called using rspec如何测试使用 rspec 调用的私有方法
【发布时间】:2019-02-05 16:29:49
【问题描述】:

我试图确保在被回调调用时调用给定的方法。 基本上,我有一个 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

【问题讨论】:

标签: ruby-on-rails-4 rspec


【解决方案1】:

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

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

另一种测试方法是验证保存矩阵后是否存在可疑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

【讨论】:

  • 非常感谢!除了条件回调之外,我已经尝试过 gem 效果很好。
【解决方案2】:

也许我遗漏了一些东西,但我没有看到保存调用,你试过了吗:

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 知道你要存根那个方法,在保存之后你验证这个方法被调用了。

【讨论】:

    猜你喜欢
    • 2013-04-08
    • 2011-08-03
    • 1970-01-01
    • 2011-05-15
    • 2019-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-13
    相关资源
    最近更新 更多