简体   繁体   English

控制器中的Ruby on Rails方法

[英]Ruby on Rails Method Mocks in the Controller

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. 我试图在我的一个rails控制器(在本例中为Instagram.get_access_token)中模拟对外部API的方法调用,但遇到了一些麻烦。 As written, the code is still calling the real Instagram.get_access_token method. 按照编写,代码仍在调用真实的Instagram.get_access_token方法。 How do I have the controller use my simple mock instead? 如何让控制器使用我的简单模拟代替?

sessions_controller.rb: 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: 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

Try: 尝试:

Instagram.stub(:get_access_token) { response }

Do you have the same result? 你有相同的结果吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM