【问题标题】:Capybara/rspec configuration issueCapybara/rspec 配置问题
【发布时间】:2025-12-28 12:00:06
【问题描述】:

当我尝试使用 Capybara 运行我的功能规范时,我得到一个

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

错误。我知道这是没有正确配置 capybara 的问题,否则它会有一个 visit 方法。

这是我的 gemfile 的相关部分:

group :test, :development do
  gem 'rspec-rails', '~> 2.0'
  gem 'factory_girl_rails', ">= 4.2.0"
  gem 'guard-rspec', "~> 0.7.0"
end

group :test do
  gem 'faker', '~> 1.0.1'
  gem 'capybara', git: 'https://github.com/jnicklas/capybara', ref: '7fa75e55420e'
  gem 'database_cleaner', '~> 0.7.2'
  gem 'launchy', '~> 2.1.0'
  gem 'shoulda-matchers'
end

使用我从this article 获得的水豚 ref 升级到 Capybara 2.0。

这是我的规格:

# spec/features/create_user_spec.rb

require 'spec_helper'

feature 'Creating a user' do

  scenario 'adds a new user' do

    visit new_user_registration_path
    fill_in 'Email', :with => 'me@me.com'
    [ 'Password', 'Password confirmation' ].each { |p| fill_in p, :with => '12345678' }
    page.should have_content 'User successfully created'
    current_path.should == recipes_path

  end

end

这是我的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 'rspec/autorun'

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

# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}

RSpec.configure do |config|
  config.use_transactional_fixtures = true

  config.infer_base_class_for_anonymous_controllers = false

  config.include Capybara::DSL

  config.order = "random"
end

我尝试过的

  • 手动包括Capybara::DSL
  • 添加require_relativespec_helper 文件提供正确的路由

请告诉我我忽略了什么。

【问题讨论】:

    标签: ruby-on-rails rspec capybara


    【解决方案1】:

    你有多个 spec_helper.rb 文件

    尝试给予

    require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
    

    或给出完整路径...

    下划线没有被渲染。

    【讨论】:

    • 只有一个spec_helper.rb 文件,当我使用expand_path 方法时,我得到uninitialized constant FILE