NoMethodError undefined method `shared_examples_for’ for main:Object for bundle gem rspec


If you create a gem stub using bundle gem thing and select rspec as your test suite, you may get an error similar to the following:

❯ bundle exec rspec

An error occurred while loading ./spec/thing_spec.rb.
Failure/Error:
  shared_examples_for 'saying hello' do
    puts "hi"
  end

NoMethodError:
  undefined method `shared_examples_for' for main:Object
# ./spec/thing_spec.rb:1:in `<top (required)>'
No examples found.

whenever using describe, shared_examples, and shared_examples_for, etc…

After a lot of diving into rspec source code to verify where shared_examples_for was defined (rspec-core so…) I noticed the following code in the stubbed spec_helper.rb:

  # Disable RSpec exposing methods globally on `Module` and `main`
  config.disable_monkey_patching!

If you comment out config.disable_monkey_patching!, then those methods will be included at a top level.


One response to “NoMethodError undefined method `shared_examples_for’ for main:Object for bundle gem rspec”

Leave a Reply

%d bloggers like this: