Why do I get “undefined method or variable 'ex

2019-06-15 02:00发布

问题:

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.

回答1:

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


回答2:

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.



回答3:

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


回答4:

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.



回答5:

These worked form me using Ruby2/Rails4/RSpec3.0.0.beta and Capybara2.2.0.beta: ruby 2.0.0p353 (2013-11-22 revision 43784) [x86_64-linux]

  • Gemfile

    ...
    gem 'rails', '4.0.1'
    group :development, :test do
       gem 'rspec-rails','~>3.0.0.beta' 
       gem 'factory_girl_rails' 
    end                                                                                                                                 

    group :test do gem 'faker' gem 'capybara', '>=2.2.0.beta' gem 'guard-rspec' gem 'launchy' end

  • put Capybara specs in spec/features, not spec/requests.

  • Tag all the example groups in which you want to use Capybara with:

    describe "Users", :type => :feature do
      ...
    end
    

  • Add the following line to the spec_helper.rb: require 'capybara/rspec' and add the DSL to the RSpec.config block

    RSpec.configure do |config| block ... config.include Capybara::DSL