Rails - 单例 class 问题 rspec 功能

Rails - Singleton class troubles with rspec feature

我在测试依赖单例的功能时遇到问题 class。 class (ERPDao) 是一个具有不同方法的套件,可帮助应用程序使用 Faraday gem 通过 REST 服务连接到外部 ERP。 URLMaker 是构建请求字符串的助手 class。当我尝试 运行 依赖于其中一种方法的功能规范时,我在 rspec 中收到以下消息:

 Failure/Error: result = ERPDao.instance.get_credit_info(erp_id)

 NoMethodError:
   undefined method `instance' for ERPDao:Class
   Did you mean?  instance_of?
   Did you mean?  instance_of?

我的classERPDao

class ERPDao
def initialize
    @end_points = EndPoint.first
    @connection = Faraday.new(:url => @end_points.url_base, request: {
      open_timeout: 10,   # opening a connection
      timeout: 10         # waiting for response
    })
end
@@instance = ERPDao.new

def self.instance
    return @@instance
end

def get_credit_info(erp_id)
    begin
        return @connection.get URLMaker.instance.get_uri('credit_info', erp_id)
    rescue Faraday::Error::ConnectionFailed => e
        puts "Connection failed: #{e}"
        return 0, false, 0
    end
end

    ...
end

我的rails_helper.rb

require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
require 'support/factory_bot'
require 'support/wait_for_ajax'
ActiveRecord::Migration.maintain_test_schema!

RSpec.configure do |config|
  config.fixture_path = "#{::Rails.root}/spec/fixtures"
  config.use_transactional_fixtures = false

  config.before :suite do
    DatabaseCleaner.strategy = :truncation
  end

  config.before :each do
    DatabaseCleaner.clean
  end
  config.infer_spec_type_from_file_location!
  config.filter_rails_from_backtrace!
  config.include Warden::Test::Helpers

  config.include Devise::TestHelpers, type: :controller

  Shoulda::Matchers.configure do |config|
    config.integrate do |with|
      with.test_framework :rspec
      with.library :rails
    end
  end
  Capybara.javascript_driver = :webkit

  Capybara::Webkit.configure do |config|
    config.debug = false
    config.allow_unknown_urls
    config.skip_image_loading
    config.timeout = 15
    config.raise_javascript_errors = false
  end
end

我的 rails 版本是 4.2.6,ruby 2.3.1,factory_bot 4.8.2 和 rspec-rails 3.7。 有人知道这个错误吗? 谢谢!

ERPDao [也] 在其他地方定义。也许有人决定通过重新打开 class like

来为其添加方法
class ERPDao
  def some_new_method
    ...
  end
end

不要那样做。改为使用模块和前缀。

module HasMyNewMethod
  def some_new_method
    ...
  end
end
ERPDau.prepend HasMyNewMethod

否则您最终会不小心引用 class 的重新打开并成为定义 - 因此自动加载器不会加载它,因为它已经定义了。

在您的代码库中搜索 'class ERPDao'。修改不是初始声明的。