Rspec and Capybara undefined local variable or met

2019-05-11 00:59发布

Hi I tried to start my first RoR project, and get stuck, a the begining :(

I have capybara gem in my Gemfile :

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

I added capybara on my first line in 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

and added it to 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'

But when I tried to test the right title in 'spec/controller/static_pages_controller_spec.rb :

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

I got an error: undefined local variable or method page

I tired to solve this by my self but everyone only says about adding to require "capybara/rspec"

1条回答
Rolldiameter
2楼-- · 2019-05-11 01:09

Controller specs don't have access to Capybara's helpers: feature specs do.

You can create a test file at /spec/features/static_pages_spec.rb similar to the following to make use of 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
查看更多
登录 后发表回答