Capybara: undefined method 'visit'

2019-01-21 09:30发布

When running my specs with rspec & capybara, it can't find capybara's visit method. Is there another initialization step I need to do?

$bundle exec rspec spec
/home/brian/projects/expense_track/expense_track/spec/requests/homepage_spec.rb:6:in `block (2 levels) in <top (required)>': undefined method `visit' for #<Class:0xb6572b8> (NoMethodError)

Gemfile:

group :test, :development do
  gem "rspec-rails"
  gem "capybara"
end

top of my spec_helper.rb:

# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)

require 'rspec/rails'
require 'capybara/rspec'
require 'rspec/autorun'

homepage_spec.rb:

require 'spec_helper'

describe "The home page" do

  context "home page exists" do
    visit "/"
    page.should have_content("elephants")
  end
end

7条回答
聊天终结者
3楼-- · 2019-01-21 09:48

For rspec 3 and rails, make sure you are using require "rails_helper", instead of require "spec_helper".

Otherwise, review the latest changes to rspec 3 & rspec-rails and Capybara 2.0.x.

查看更多
Deceive 欺骗
4楼-- · 2019-01-21 09:49

Unfortunately this workaround doesn't do it for me. I still get

NoMethodError:
   undefined method `visit' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_1::Nested_1:0x007fbfeb535298>

The repo is public under: https://github.com/ikusei/Goldencobra_Newsletter You need to look at the branch '28817499-subscribe'

edit: If i put include Capybara::DSL inside my describe block it works.

but including Capybara::DSL in the global scope is not recommended!

Because I do not know a good way.

查看更多
手持菜刀,她持情操
5楼-- · 2019-01-21 09:50

A few things to note here :

  1. The changes in Capybara 2.0.x are documented here https://github.com/rspec/rspec-rails/blob/master/Capybara.md . There are changes in the spec directory structure : spec/features, spec/controllers, spec/views, spec/helpers, spec/mailers.
  2. load Capybara dsl explicitly inside your spec_helper


       require 'capybara/rails'
       require 'capybara/rspec'
       include Capybara::DSL

查看更多
Lonely孤独者°
6楼-- · 2019-01-21 09:53

This worked for me.

require 'rspec/rails'
require 'rspec/autorun'
require 'capybara/rspec'
require 'capybara/rails'

RSpec.configure do |config|
  config.include Capybara::DSL, :type => :request
end

This enables you to use Capybara's helpers inside spec/requests.

查看更多
乱世女痞
7楼-- · 2019-01-21 09:56

Because RSpec.configure not including capybara DSL in spec_helper.rb

It is an ugly solution, but you can add this to your spec_helper.rb.

module ::RSpec::Core
  class ExampleGroup
    include Capybara::DSL
    include Capybara::RSpecMatchers
  end
end 

The git issue for this:

https://github.com/rspec/rspec-rails/issues/503

查看更多
登录 后发表回答