如何在RSpec中模拟方法调用

时间:2019-04-30 22:40:50

标签: ruby-on-rails rspec mocking

我需要模拟RSpec中的方法调用。我知道如何针对常规方法调用。但是这个方法调用是根据我在错误日志中得到的反馈来链接的。我该如何嘲笑它?

日志

module Facebook
  config = Rails.application.settings

  APP_ID = config[:facebook][:id]
  SECRET = config[:facebook][:secret]

  REWARDS_APP_ID = config[:facebook_rewards][:id]
  REWARDS_SECRET = config[:facebook_rewards][:secret]

  def self.config_for_app(app)
    app_id = app ? "#{app.upcase}_APP_ID" : 'APP_ID'
    secret = app ? "#{app.upcase}_SECRET" : 'SECRET'

    [const_get(app_id), const_get(secret)]
  end

  def self.oauth_for_app(app)
    _, app = /facebook_app_(.+)/.match(app).to_a
    Koala::Facebook::OAuth.new *config_for_app(app)
  end
end

facebook.rb

before do
  setup_omniauth
  allow(Koala::Facebook::OAuth).to receive(:refresh_facebook_token).and_return(true)
end

我尝试了

Get-ItemProperty 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*',
    'HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*' |
    Select-Object DisplayName, DisplayVersion, Publisher, InstallDate |
    Sort-Object InstallDate -descending |
    Where-Object {
        $_.InstallDate -gt (Get-Date).Date.AddDays(-5).ToString('yyyyMMdd')
    } 

2 个答案:

答案 0 :(得分:3)

这是一个很好的用例,例如使IMO倍增

oauth = instance_double(Koala::Facebook::OAuth)
allow(Koala::Facebook::OAuth).to receive(:new).with(config).and_return(oauth)
allow(oauth).to receive(:some_other_method)

答案 1 :(得分:1)

我能够使用receive_message_chain

找到其他解决方案
  allow(Facebook).to receive_message_chain(:oauth_for_app, :exchange_access_token_info).and_return('access_token' => '123', 'expires' => 500_000)