如何在 RSpec 中模拟方法调用
How to mock method call in RSpec
我需要在 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
这是一个很好的用例,例如双打 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)
我能够使用 receive_message_chain
找到另一个解决方案
allow(Facebook).to receive_message_chain(:oauth_for_app, :exchange_access_token_info).and_return('access_token' => '123', 'expires' => 500_000)
我需要在 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
这是一个很好的用例,例如双打 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)
我能够使用 receive_message_chain
allow(Facebook).to receive_message_chain(:oauth_for_app, :exchange_access_token_info).and_return('access_token' => '123', 'expires' => 500_000)