Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to require file from `gem` which are not under `lib` directory?

I want to write spec for my rubocop custom cop. This gem has handy helpers defined here. I want to require it. How to achieve what?

I've tried to use Gem.find_files, and this gives me ability to require any file in that gem, but only under lib directory.

For example:

# 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

The following describes why I need it. I have 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

When I try plain require:

require 'rubocop/spec/support/cop_helper'

I receive error:

/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
like image 365
Astery Avatar asked Mar 30 '15 14:03

Astery


People also ask

Where are RubyGems stored?

When you use the --user-install option, RubyGems will install the gems to a directory inside your home directory, something like ~/. gem/ruby/1.9. 1 . The commands provided by the gems you installed will end up in ~/.

What is require RubyGems?

Requiring code RubyGems modifies your Ruby load path, which controls how your Ruby code is found by the require statement. When you require a gem, really you're just placing that gem's lib directory onto your $LOAD_PATH . Let's try this out in irb .

How do I push a gem to RubyGems?

Note that you need an account at RubyGems.org to do this. From the main menu, select Tools | Gem | Push Gem. In the Run tool window, specify your RubyGems credentials. Your gem will be published to RubyGems.org.

What are gem files?

A Gemfile is a file that is created to describe the gem dependencies required to run a Ruby program. A Gemfile should always be placed in the root of the project directory.


2 Answers

I found a solution that I think is a little more syntactically elegant:

gem_dir = Gem::Specification.find_by_name("my_gem").gem_dir
require "#{gem_dir}/spec"
like image 86
ledhed2222 Avatar answered Sep 28 '22 05:09

ledhed2222


I was so blinded, I already have path to file and able to get relative from it.

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"
like image 26
Astery Avatar answered Sep 28 '22 07:09

Astery