1

我想要什么:每次运行测试时调用外部 API 以返回相同的东西我得到了什么:第一次 VCR 保存它,第二次 Typhoeus 返回错误

发生的情况是我运行一次测试,它发出实际请求(当我创建组织和用户时发生),然后当我再次运行它时,它无法正确解析请求。

第一次运行:

1) AccountSettingsController GET #show responds successfully with an HTTP 200 status code
   Failure/Error: expect(response).to be_success
     expected success? to return true, got false
   # ./spec/controllers/account_settings_spec.rb:12:in `block (3 levels) in <top (required)>'

以下所有运行,直到我删除磁带:

1) AccountSettingsController GET #show responds successfully with an HTTP 200 status code
   Failure/Error: organization = Fabricate(:organization)
   NoMethodError:
     undefined method `>=' for nil:NilClass
   # ./app/models/hand.rb:45:in `create'
   # ./app/models/hand.rb:64:in `save'
   # ./app/models/hand.rb:70:in `save!'
   # ./spec/controllers/account_settings_spec.rb:6:in `block (3 levels) in <top (required)>'

这可以追溯到这些行(来自我使用的私人宝石)

def create(values)
  response = Typhoeus.post(resource_url, {body: values.to_json}.merge(headers))

  process_as_json response.options[:response_body]
end

def process_as_json(response)
  if !response.empty?
    JSON.parse(response)
  else
    nil
  end
end

版本:

  • 录像机 (2.9.0)
  • 网络模型 (1.18.9)
  • 台风 (0.6.8)

设置:

# spec/spec_helper.rb

require "simplecov"
SimpleCov.start "rails"

ENV["RAILS_ENV"] ||= "test"
require File.expand_path("../../config/environment", __FILE__)

require "rspec/rails"
require "rspec/autorun"
require "capybara/rspec"
require "webmock/rspec"

Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }

Fabrication.configure do |config|
  config.path_prefix = Rails.root
end

VCR.configure do |config|
  config.cassette_library_dir = "spec/vcr_cassettes"
  config.hook_into :webmock
  config.configure_rspec_metadata!
end

RSpec.configure do |config|
  config.order = "random"
  config.treat_symbols_as_metadata_keys_with_true_values = true
end

测试:

# spec/controllers/account_settings_spec.rb

require "spec_helper"

describe AccountSettingsController do
  describe "GET #show" do
    it "responds successfully with an HTTP 200 status code", :vcr do
      organization = Fabricate(:organization)
      user = Fabricate(:user, organization_id: organization.id)

      get :show

      expect(response).to be_success
      expect(response.status).to eq(200)
    end
  end
end
4

1 回答 1

1

无法从您提供的详细信息中明确回答您的问题,但这里有一些建议:

  • 使用debug_logger 选项获取 VCR 正在执行的操作的详细输出;这可以给你一个关于正在发生的事情的提示。
  • 尝试使用hook_into :typhoeus而不是hook_into :webmock. 当您直接连接到 typhoeus rahter 时,VCR 能够比使用 webmock 作为中间层更准确地录制和播放。
于 2014-05-24T05:05:32.270 回答