ruby - 如何从 `gem` 中获取不在 `lib` 目录下的文件?

标签 ruby rspec rubygems rubocop

我想为我的 rubocop 编写规范自定义警察。这个 gem 定义了方便的助手 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

最佳答案

我找到了一个我认为语法更优雅的解决方案:

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

关于ruby - 如何从 `gem` 中获取不在 `lib` 目录下的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29348751/

相关文章:

ruby-on-rails - Rails 将参数/参数传递给 ActiveRecord 回调函数

ruby - 我可以使用 Hpricot 查找任何/大多数网站的主要文章文本吗?

ruby-on-rails - 调试 Cucumber 步骤定义

ruby - 在 ruby​​ 测试中启动 Web 服务器

ruby-on-rails - Rolify和CanCan有什么意义?

ruby - 编写模拟器并需要能够引用 Ruby 中的方法/函数

ruby - RSpec:每次指定对具有不同参数的方法的多次调用

ruby - 如何在 Rspec 中只运行特定的测试?

mysql - mysql和mysql2 gem有什么区别

ruby - 在 CentOs 5 上安装 RubyGem