本文介绍了控制器中的Ruby on Rails方法模拟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的一个rails控制器(在本例中为Instagram.get_access_token)中模拟对外部API的方法调用,但遇到了一些麻烦.按照编写的方式,该代码仍在调用真实的Instagram.get_access_token方法.如何让控制器使用我的简单模拟代替?

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?

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

推荐答案

尝试:

Instagram.stub(:get_access_token) { response }

结果是否相同?

这篇关于控制器中的Ruby on Rails方法模拟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 05:48