Мне очень нравится capybara и rpsec, и я могу написать с ними отличные интеграционные тесты. Тем не менее, я немного смущен чем-то. Может быть, я неправильно здесь, но мне кажется, после того, как я установил водосвинку, и у меня есть свои функции в spec/features
, методы Капибара, такие как visit
доступны спецификации внутри spec/features
(например spec/features/controllers/statuses_spec.rb
), но RSpec методы, такие как route_to
теперь недоступны этим спецификациям!Ошибка метода при использовании capybara и rspec
Что это значит? Может ли capybara предоставлять методы, которые компенсируют мои недоступные методы rspec? Например, visit
, а не get
?
Это не кажется очень интуитивным. Надеюсь, что я делаю что-то неправильно в отношении моей установки:
Gemfile:
source 'https://rubygems.org'
group :development do
gem 'capistrano'
gem 'guard-rspec'
gem 'rb-fsevent'
gem 'debugger'
end
group :development, :test do
gem 'rspec-rails', '~> 2.14.0'
gem 'sqlite3'
end
group :test do
gem 'factory_girl_rails'
gem 'capybara', '~> 2.2.0'
# gem "capybara-webkit"
gem 'launchy'
gem 'database_cleaner'
end
group :production do
gem 'pg'
end
gem 'rails', '4.0.1'
gem 'sass-rails', '~> 4.0.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.0.0'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 1.2'
group :doc do
gem 'sdoc', require: false
end
gem 'devise'
# Use puma as the app server
# gem 'puma'
спецификации/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'
# 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 }
# Checks for pending migrations before tests are run.
# If you are not using ActiveRecord, you can remove this line.
ActiveRecord::Migration.check_pending! if defined?(ActiveRecord::Migration)
RSpec.configure do |config|
# ## Mock Framework
#
# If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
#
# config.mock_with :mocha
# config.mock_with :flexmock
# config.mock_with :rr
config.before(:suite) do
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.clean_with(:truncation)
end
config.before(:each) do
Capybara.run_server = true
Capybara.javascript_driver = :webkit
Capybara.default_selector = :css
Capybara.server_port = 7171
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.include RSpec::Rails::RequestExampleGroup, type: :feature
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = true
# If true, the base class of anonymous controllers will be inferred
# automatically. This will be the default behavior in future versions of
# rspec-rails.
config.infer_base_class_for_anonymous_controllers = false
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = "random"
end
SPEC/особенности /controllers/statuses_spec.rb
require 'spec_helper'
describe StatusesController do
describe "routing" do
# contains only capybara methods and so it passes
it "contains welcome message" do
visit("/statuses")
page.should have_content("All of our statuses ")
end
# contains rspec methods and so I recieve a no method failure
it "responds with 200" do
get("/statuses").should respond_with 200
end
end
end
Выход:
13:17:44 - INFO - Running: spec/features/controllers/statuses_spec.rb
.F
Failures:
1) StatusesController routing responds with 200
Failure/Error: get("/statuses").should respond_with 200
NoMethodError:
undefined method `respond_with' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_1:0x00000101787560>
# ./spec/features/controllers/statuses_spec.rb:12:in `block (3 levels) in <top (required)>'
Finished in 0.40626 seconds
2 examples, 1 failure
Я уверен, что это как-то связано с размещением этих спецификаций в каталоге «features», но мне нужно поместить их в каталог «features», чтобы использовать методы capybara.
Так что мне нужно разместить все спецификации, которые используют методы capybara в «функциях» и все, что использует методы rspec в «spec»? Надеюсь нет. Как настроить мои файлы?
Вы смешиваете методы для испытаний контроллеров и методы для спецификаций функций – apneadiving
Я только начал использовать rspec и capybara несколько часов назад. Не могли бы вы объяснить, пожалуйста? – Starkers
, чтобы быть коротким: в папке 'specs/features' вы должны использовать' visit' только с путями, заполнять формы и кликать и т. Д. В 'specs/controller' использовать' get' или любой http-глагол, чтобы убедиться, что ваш контроллер ведет себя так, как вы пожелаете – apneadiving