问题
I'm trying to mock a method call to an outside API inside one of my rails controllers (in this case, Instagram.get_access_token) and I'm having some trouble. As written, the code is still calling the real Instagram.get_access_token method. How do I have the controller use my simple mock instead?
sessions_controller.rb:
class SessionsController < ApplicationController
require 'instagram'
include ApplicationHelper
def auth_callback
response = Instagram.get_access_token(params[:code],
redirect_uri: auth_callback_url)
#<snipped extra code>
end
end
sessions_controller_spec.rb:
require 'spec_helper'
require 'ostruct'
describe SessionsController do
describe "GET #auth_callback" do
context "when there is an existing user" do
let(:response) { OpenStruct.new(access_token: "good_access_token") }
it "parses an access_token from the get response" do
Instagram.should_receive(:get_access_token).and_return(response)
#<snipped extra code>
end
end
end
end
回答1:
Try:
Instagram.stub(:get_access_token) { response }
Do you have the same result?
来源:https://stackoverflow.com/questions/16628739/ruby-on-rails-method-mocks-in-the-controller