RSpec & Capybara: How to fix undefined method `feature' for main:Object (NoMethodError)

Published

While working on the Ohana API during the Code for America fellowship, I came across a strange situation. My feature specs didn’t include require "spec_helper" at the top of each file, yet I was able to run all of the specs like so:

$ rspec

Or just all of the feature specs:

$ rspec spec/features

And individual ones as well:

$ rspec spec/features/signin_spec.rb

Then when I cloned the repo to a new directory (to test the installation instructions in the README), I noticed that I could no longer run specific tests. If I tried to run rspec spec/features/signin_spec.rb for example, I would get this error:

~/ohana-api/spec/features/signin_spec.rb:1:in `<top (required)>':
undefined method `feature' for main:Object (NoMethodError)

The reason why this worked in the original directory is because I had a file called .rspec that automatically required spec_helper in all tests. At the time, spec_helper.rb also required Rails, and everything else related to RSpec. I had the following line in my .rspec file:

--require spec_helper

The reason why this stopped working in the new directory is because this file was included in the project’s .gitignore, meaning it was not checked into Git, and therefore didn’t get copied into the new directory after cloning the repo.

The solution was to either add the .rspec file and remove it from .gitignore, or manually add require "spec_helper" to the top of each feature spec.

Later on, I moved the Rails-specific code to a separate rails_helper.rb file. This allowed us to selectively add require "rails_helper" only in tests that depend on Rails, which avoids unnecessarily slowing down the test suite.