【问题标题】:How to mock method call in RSpec如何在 RSpec 中模拟方法调用
【发布时间】:2019-04-30 22:40:50
【问题描述】:

我需要在 RSpec 中模拟一个方法调用。我知道如何为正常的方法调用做到这一点。但是这个方法调用是根据我在错误日志中得到的反馈链接起来的。如何模拟它?

日志

Failure/Error: response = Facebook.oauth_for_app(provider).exchange_access_token_info(token)

     Koala::Facebook::OAuthTokenRequestError:
       type: OAuthException, code: 190, message: Invalid OAuth access token. [HTTP 400]

facebook.rb

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

我试过了

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

【问题讨论】:

    标签: ruby-on-rails rspec mocking


    【解决方案1】:

    这是一个很好的用例,例如双打 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)
    

    【讨论】:

    • 有道理,但现在我收到错误uninitialized constant Koala::Facebook::Oauth。即使我将require "koala" 添加到文件顶部。
    • 新错误对您有意义吗?就是说*config_for_app(app)和你在测试中的config不一样。
    • 这可行,但我找到了一个更简单的解决方案。将在下面发布
    【解决方案2】:

    我能够使用receive_message_chain找到另一个解决方案

      allow(Facebook).to receive_message_chain(:oauth_for_app, :exchange_access_token_info).and_return('access_token' => '123', 'expires' => 500_000)
    

    【讨论】:

      猜你喜欢
      • 2013-09-11
      • 1970-01-01
      • 1970-01-01
      • 2015-08-23
      • 2022-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-17
      相关资源
      最近更新 更多