d0nutz1
d0nutz1

Reputation: 417

Writing tests in RSpec for a Gem

I'm trying to write RSpec tests for a gem I wrote, but I am having trouble getting the tests to recognize the Modules I wrote and the methods related to those Modules.

Here is my spec_helper.rb:

require 'rspec'

RSpec.configure do |config|

end

My Spec file:

require 'spec_helper'

describe MyCompany::SomeHelper do
  describe '#self.get_token' do
    token = MyCompany::SomeHelper.get_token
  end
end

When I run the test, I get this error message: undefined method `get_token' for MyCompany::SomeHelper:Module (NoMethodError).

The gem itself works fine when I include it in another application though. I think I may not be configuring something in RSpec correctly, can anyone help?

Upvotes: 2

Views: 1457

Answers (2)

iain
iain

Reputation: 16274

The confusion is probably because of Rails, because Rails loads everything and requiring 'spec_helper' is the only thing you need to do there.

RSpec automatically adds the lib directory to your load path, so you can require your code from your specs with ease.

Let's say you have this file to be tested: lib/my_gem_name/my_class.rb, then put this code on top of your spec:

require 'my_gem_name/my_class'

If you're not going to configure anything in your spec_helper, you don't need to create it and require it. In fact, I would recommend against it if you're doing purely isolated tests.

Upvotes: 2

jboursiquot
jboursiquot

Reputation: 1271

You need to require the file containing the definition of your SomeHelper module. Neither your spec_helper nor your spec file pull it in. This assumes you're writing your tests in the same project as your gem.

If you've already packaged the gem and are trying to test it from a different project, then require the gem somewhere in your load path.

Upvotes: 1

Related Questions