Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get "undefined method or variable 'example'" in RSpec 3.0?

Tags:

rspec

capybara

After upgrading to RSpec 3.0, I got the following message:

 Failure/Error: Unable to find matching line from backtrace
 NameError:
   undefined local variable or method `example' for #<RSpec::ExampleGroups::Anonymous:0x007f9ae985b548>

The message persisted even after reducing the spec to the following:

describe "" do
  it "" do
  end
end

I did notice capybara was near the top of the stack, as follows:

 # /Users/palfvin/.rvm/gems/ruby-2.0.0-p247@botmetrics/gems/capybara-2.1.0/lib/capybara/rspec.rb:20:in `block (2 levels) in <top (required)>'

in case that helps.

like image 228
Peter Alfvin Avatar asked Dec 06 '13 00:12

Peter Alfvin


4 Answers

I had a similar problem with a before hook.

It seems that RSpec < 3 provided an example object in every hook, like this:

config.before(:each) do
  if example.metadata[:js] # <--- this fails!
    # do something
  end
end

In RSpec >= 3, you have to pass an explicit example parameter to the block:

config.before(:each) do |example| # <--- see here!
  if example.metadata[:js]
    # do something
  end
end
like image 140
Joshua Muheim Avatar answered Nov 19 '22 12:11

Joshua Muheim


This error results from installing RSpec 3.0.0.beta while continuing to run Capybara 2.1.0. If you install Capybara 2.2.0.beta, the error will go away.

like image 32
Peter Alfvin Avatar answered Nov 19 '22 10:11

Peter Alfvin


For some unrelated reasons I couldn't upgrade Capybara, so I use this monkey patch (add in a file in spec/support):

module Capybara
  module DSL
    def example
      RSpec.current_example
    end
  end
end
like image 3
robd Avatar answered Nov 19 '22 11:11

robd


I had the same error, not in Capybara, but in my specs. I did a find and replace of example. to RSpec.current_example. and it works now. Seems example is now RSpec.current_example.

like image 2
Kirk Avatar answered Nov 19 '22 10:11

Kirk