Ruby on Rails Method Mocks in the Controller

和自甴很熟 提交于 2020-01-16 21:53:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!