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

时间:2015-03-30 14:23:16

标签: ruby rspec rubygems rubocop

我想为我的rubocop自定义警察编写规范。这个宝石有定义here的方便助手。我想要它。如何实现目标?

我尝试使用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

以下描述了我需要它的原因。我有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

当我尝试普通需求时:

require 'rubocop/spec/support/cop_helper'

我收到错误:

/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

2 个答案:

答案 0 :(得分:7)

我发现了一个我认为在语法上更优雅的解决方案:

gem_dir = Gem::Specification.find_by_name("my_gem").gem_dir
require "#{gem_dir}/spec"

答案 1 :(得分:4)

我是如此盲目,我已经有了归档的路径并且能够从中得到亲戚。

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"