Rspec 和 Capybara 未定义的局部变量或方法`page'

Rspec and Capybara undefined local variable or method `page'

嗨,我试图开始我的第一个 RoR 项目,但一开始就卡住了:(

我的 Gemfile 中有水豚 gem :

group :development, :test do
  gem 'byebug'
  gem 'web-console'
  gem 'spring'
  gem 'rspec-rails'
  gem 'capybara'  
  gem 'factory_girl_rails'
  gem 'database_cleaner'   
end

我在 spec_helper 的第一行添加了水豚:

require "capybara/rspec"

RSpec.configure do |config|
  # rspec-expectations config goes here. You can use an alternate
  # assertion/expectation library such as wrong or the stdlib/minitest
  # assertions if you prefer.
  config.expect_with :rspec do |expectations|
    # This option will default to `true` in RSpec 4. It makes the `description`
    # and `failure_message` of custom matchers include text for helper methods
    # defined using `chain`, e.g.:
    #     be_bigger_than(2).and_smaller_than(4).description
    #     # => "be bigger than 2 and smaller than 4"
    # ...rather than:
    #     # => "be bigger than 2"
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end

并将其添加到 rails_helper:

# 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'


# Add additional requires below this line. Rails is not loaded until this point!
require 'capybara/rspec'
require 'capybara/rails'

但是当我试图在'spec/controller/static_pages_controller_spec.rb 中测试正确的标题时:

it "have propper title" do
    get :home
    expect(page).to have_title "Testowy tytuł" 
end

我收到一个错误:未定义局部变量或方法页面

我厌倦了自己解决这个问题,但每个人都只说要添加到 require "capybara/rspec"

Controller specs don't have access to Capybara's helpers: feature specs做。

您可以在 /spec/features/static_pages_spec.rb 创建一个类似于以下内容的测试文件来使用 Capybara:

require "rails_helper"

RSpec.feature "Static pages", :type => :feature do
  scenario "Visiting the home page" do
    visit "/"
    expect(page).to have_title "Testowy tytuł" 
  end
end