Capybara methods are undefined

2019-02-19 09:03发布

问题:

I cannot get capybara to work. I am using capybara 2.0.0

I get this error

Failure/Error: visit "/users/sign_in"
     NoMethodError:
       undefined method `visit' for #<RSpec::Core::ExampleGroup::Nested_21:0x007fdda4c6eba0>

on this spec

spec/requests/forgot_password_spec.rb

describe "forgot password" do
  it "redirects user to users firms subdomain" do
    visit "/users/sign_in"  
  end
end

I do not get any errors that it cannot find capybara and it's included in the spec_helper.rb

spec_helper.rb

require 'rubygems'
require 'spork'
require 'database_cleaner'
Spork.prefork do
 ENV["RAILS_ENV"] ||= 'test'
 require File.expand_path("../../config/environment", __FILE__)
 require 'rspec/rails' 
 require 'capybara/rspec'
 require 'rspec/autorun'
 require 'factory_girl'


 Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}

 RSpec.configure do |config|
   config.include Devise::TestHelpers, :type => :controller
   config.extend ControllerMacros, :type => :controller
   config.include RequestMacros, :type => :request
   config.mock_with :rspec

   config.use_transactional_fixtures = false

   config.before(:suite) do
     DatabaseCleaner.strategy = :truncation
   end

   config.before(:each) do
     DatabaseCleaner.start
   end

   config.after(:each) do
     DatabaseCleaner.clean
   end
   config.infer_base_class_for_anonymous_controllers = false
 end
 Spork.each_run do
   FactoryGirl.reload  
 end
 end

Has anybody else encountered this?

回答1:

If you've got version >= 2.0, any tests that use Capybara methods like visit should go under a spec/features directory, and not under spec/requests, where they'd normally reside in Capybara 1.1.2.

Have a look at the following links for more information:

  • rspec-rails and capybara 2.0: what you need to know
  • rspec-rails gem Capybara page

If you don't want to use a spec/features directory, you should be able to mark a test as a feature in the following way and have Capybara methods work:

describe "Some action", type: :feature do
  before do
    visit "/users/sign_in"
    # ...
  end
  # ...
end


回答2:

In my case, I got this error because I forgot to putrequire "spec_helper" at the top of my new spec file.

I've done it enough times that I'm adding an answer to an already answered question in hopes that it helps some other knucklehead (or most likely me searching this again in the future).