简体   繁体   English

Rspec测试不符合我期望的双行为

[英]Rspec test double not behaving as I would expect inside rails controller

Controller action: 控制器动作:

class GoogleOauth2sController < ApplicationController
  def new
    google_drive_oauth2 = GoogleDriveOauth2.new
    redirect_to google_drive_oauth2.authorization_uri
  end
end

test: 测试:

require 'spec_helper.rb'

describe GoogleOauth2sController do
  let(:google_drive_oauth2) { double("GoogleDriveOauth2", :authorization_uri => "www.reddit.com") }

  describe "GET #new" do
    it "should redirect user to google oauth2 authorization page" do
      get :new
      expect(response.redirect_url).to include("accounts.google.com/o/oauth2/auth")
    end
  end
end

I would expect this test to FAIL, because i created a test double of the "GoogleDriveOauth" class and stubbed out its method to return "www.reddit.com". 我希望此测试失败,因为我创建了“ GoogleDriveOauth”类的测试双倍,并将其方法存根以返回“ www.reddit.com”。 Yet the test passe, and calls out to the google oauth2 auth page. 测试通过了,并调出了Google oauth2身份验证页面。

My goal is to avoid making the api calls to Google in order to form the URI in the first place (the responsibility of the GoogleDriveOauth2 class). 我的目标是避免对Google进行api调用,以便首先形成URI(GoogleDriveOauth2类的职责)。 As far as i can tell from the documentation this should stub out the method, what i'm i missing? 据我可以从文档中得知,这应该解决该方法,我想念的是什么?

You need to inject the double into your test. 您需要将双精度注入您的测试中。 RSpec doesn't know when/where the double should be used. RSpec不知道何时/何处应该使用double。 Try this: 尝试这个:

describe GoogleOauth2sController do
  let(:google_drive_oauth2) { double("GoogleDriveOauth2", :authorization_uri => "www.reddit.com") }

  describe "GET #new" do
    it "should redirect user to google oauth2 authorization page" do
      expect(GoogleDriveOauth2).to receive(:new).and_return(google_drive_oauth2)
      get :new
      expect(response.redirect_url).to include("accounts.google.com/o/oauth2/auth")
    end
  end
end

I would expect this test to fail now. 我希望此测试现在失败。

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

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