如何要求不在`lib`目录下的`gem`文件?

Ast*_*ery 7 ruby rubygems rspec rubocop

我想为我的rubocop自定义警察编写规范.这个宝石有这里定义的方便助手.我想要它.怎么实现什么?

我试过使用Gem.find_files,这使我能够要求该gem中的任何文件,但只能在lib目录下.

例如:

# this requires ...gems/rubocop-0.29.1/lib/rubocop/formatter/formatter_set.rb
require Gem.find_files('rubocop/formatter/formatter_set.rb').first
# but I need ...gems/rubocop-0.29.1/spec/support/cop_helper.rb
Run Code Online (Sandbox Code Playgroud)

以下描述了我需要它的原因.我有spec/rubocop/my_custom_cop_spec.rb

require 'spec_helper'
require ? # What I should I write?

RSpec.describe RuboCop::Cop::Style::MyCustomCop do
  it 'some test' do
    inspect_source(cop, 'method(arg1, arg2)') # This helper I want to use from rubocop spec helpers
  end
end
Run Code Online (Sandbox Code Playgroud)

当我尝试普通要求时:

require 'rubocop/spec/support/cop_helper'
Run Code Online (Sandbox Code Playgroud)

我收到错误:

/home/user/.gem/ruby/2.0.0/gems/activesupport-4.2.0/lib/active_support/dependencies.rb:274
:in `require': cannot load such file -- rubocop/spec/support/cop_helper
Run Code Online (Sandbox Code Playgroud)

led*_*222 8

我找到了一个解决方案,我认为它在句法上更优雅:

gem_dir = Gem::Specification.find_by_name("my_gem").gem_dir
require "#{gem_dir}/spec"
Run Code Online (Sandbox Code Playgroud)


Ast*_*ery 5

我太盲目了,我已经有了文件路径并且能够从中获取相对信息。

require 'pathname'
rubocop_path = Pathname.new(Gem.find_files('rubocop.rb').first).dirname
rubocop_path # => ...gems/rubocop-0.29.1/lib
require "#{rubocop_path}/../spec/support/cop_helper.rb"
Run Code Online (Sandbox Code Playgroud)