I have a docker-compose.yml as given below with service defined for selenium using selenium/standalone-chrome-debug image.
# docker-compose.yml
version: '3'
services:
webapp:
tty: true
stdin_open: true
container_name: webapp
depends_on:
- postgres
- elasticsearch
- redis
- selenium
build: .
volumes:
- .:/webapp
ports:
- "3000:3000"
entrypoint: sh /webapp/setup.sh
environment:
- REDISTOGO_URL=redis://redis:6379
- ELASTICSEARCH_URL=http://elasticsearch:9200
- SELENIUM_HOST=selenium
- SELENIUM_PORT=4444
postgres:
container_name: postgres
image: postgres:9.5.17
ports:
- "5432:5432"
volumes:
- ./postgres:/var/lib/postgresql
environment:
- POSTGRES_PASSWORD=test
- POSTGRES_USER=test
- POSTGRES_DB=test
redis:
container_name: redis
image: redis:5.0.5-alpine
command: redis-server
hostname: redis
ports:
- "6379:6379"
volumes:
- redis:/data
sidekiq:
build: .
command: bundle exec sidekiq
volumes:
- .:/webapp
depends_on:
- postgres
- redis
environment:
- REDISTOGO_URL=redis://redis:6379
elasticsearch:
image: elasticsearch:6.8.0
container_name: elasticsearch
ports:
- "9200:9200"
depends_on:
- postgres
volumes:
- esdata:/usr/share/elasticsearch/data
selenium:
image: selenium/standalone-chrome-debug
ports:
- "4444:4444"
volumes:
redis:
postgres:
esdata:
And rails_helper.rb
# rails_helper.rb
require 'database_cleaner'
require 'simplecov'
SimpleCov.start('rails') do
coverage_dir 'coverage'
add_group 'Modules', 'app/modules'
add_filter "lib/api_constraints.rb"
add_filter "app/uploaders/"
add_filter "app/models/redactor_rails/"
add_filter "app/controllers/application_controller.rb"
add_filter "app/models/application_record.rb"
add_filter "app/workers/"
end
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'spec_helper'
require 'rspec/rails'
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
# Add additional requires below this line. Rails is not loaded until this point!
require 'capybara/rspec'
require 'net_http_ssl_fix'
require 'selenium-webdriver'
require 'webdrivers/chromedriver'
require 'spree/testing_support/capybara_ext'
require 'rack_session_access/capybara'
require 'capybara-screenshot/rspec'
require 'rspec/retry'
# Add rake task example group
require 'support/tasks'
# Force lock local timezone for test environment
ENV['TZ'] = 'UTC'
Webdrivers.cache_time = 86_400
selenium_host = "http://127.0.0.1:4444/wd/hub"
unless ENV['SELENIUM_HOST'].nil?
selenium_host = "http://#{ ENV["SELENIUM_HOST"] }:4444/wd/hub"
end
Capybara.register_driver :selenium_chrome do |app|
caps = Selenium::WebDriver::Remote::Capabilities.chrome(
browserName: 'chrome',
"chromeOptions" => {
args: ['headless','no-sandbox','disable-gpu','window-size=1920x1080']
}
)
Capybara::Selenium::Driver.new(
app,
browser: :chrome,
url: selenium_host,
desired_capabilities: caps
)
end
Capybara.server = :puma, { Silent: true }
Capybara.javascript_driver = :selenium_chrome
Capybara.save_path = "#{ Rails.root }/tmp/screenshots/"
Capybara.raise_server_errors = false
Capybara.default_max_wait_time = 10
Capybara.asset_host = 'http://localhost:3000'
Capybara.configure do |config|
config.match = :prefer_exact
config.ignore_hidden_elements = false
config.visible_text_only = true
# accept clicking of associated label for checkboxes/radio buttons (css psuedo elements)
config.automatic_label_click = true
end
Capybara.always_include_port = true
# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
#
# The following line is provided for convenience purposes. It has the downside
# of increasing the boot-up time by auto-requiring all files in the support
# directory. Alternatively, in the individual `*_spec.rb` files, manually
# require only the support files necessary.
#
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
# Checks for pending migration and applies them before tests are run.
# If you are not using ActiveRecord, you can remove this line.
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
config.expect_with :rspec do |c|
# enable both should and expect
c.syntax = [:should, :expect]
end
# 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
config.append_after(:each) do
Capybara.reset_sessions!
end
config.include Capybara::DSL
config.order = "random"
config.use_transactional_fixtures = false
config.before(:suite) do
DatabaseCleaner.clean_with(:truncation)
# compile front end
WebpackerHelper.compile_once
# disable searchkick callbacks, now enabled by using search hook
Searchkick.disable_callbacks
end
# hook for enabling searchkick callbacks
config.around(:each, search: true) do |example|
Searchkick.callbacks(true) do
example.run
end
end
config.before(:each) do
DatabaseCleaner.strategy = Capybara.current_driver == :rack_test ? :transaction : :truncation
DatabaseCleaner.clean
DatabaseCleaner.start
DownloadHelper.clear_downloads
Factory.seed_data
end
config.after(:each) do
Capybara.app_host = nil # don't change me, explicitly set host in each spec appropriately
DatabaseCleaner.clean
Timecop.return
end
config.include DeviseHelpers
config.include Devise::Test::ControllerHelpers, type: :controller
config.include CommonHelper
config.include ImageHelper
config.include CommonSpecHelper
config.include ReactComponentHelper
config.include BraintreeHelper
config.include BookingSpecHelper
config.include CapybaraRspecExt
config.include DownloadHelper
config.include ActionView::Helpers::NumberHelper
config.include ActionView::Helpers::DateHelper
config.infer_spec_type_from_file_location!
# Filter lines from Rails gems in backtraces.
config.filter_rails_from_backtrace!
# arbitrary gems may also be filtered via:
# config.filter_gems_from_backtrace("gem name")
# Suppress Braintree noise
null_logger = Logger.new("/dev/null")
null_logger.level = Logger::INFO
Braintree::Configuration.logger = null_logger
config.after(:example, :on_fail => :screenshot) do |example|
full_screenshot if example.exception
end
config.after(:example, :on_fail => :open_page) do |example|
save_and_open_page if example.exception
end
# set parallel env for searchkick
Searchkick.index_suffix = ENV['TEST_ENV_NUMBER']
# show retry status in spec process
config.verbose_retry = true
# default number of retries
config.default_retry_count = 0
# sleep for 1 seconds before retry
config.default_sleep_interval = 1
# Retry failing specs (conditions to retry are set in config.retry_count_condition)
config.around :each do |ex|
ex.run_with_retry
end
# Retry failing JS specs or failing specs with specific exception
config.retry_count_condition = proc do |ex|
if (ex.metadata[:js] || [Net::ReadTimeout].include?(ex.exception.class)) && !ex.metadata[:on_fail]
nil # will fallback to config.default_retry_count
else
0 # no retries if conditions not matched
end
end
# callback to be run between retries
config.retry_callback = proc do |ex|
Capybara.reset!
end
end
When I run docker-compose exec webapp rspec spec/feature/test_spec.rb for feature spec with js: true it fails with following stacktrace:
Failure/Error: ex.run_with_retry
Selenium::WebDriver::Error::WebDriverError:
<unknown>: Failed to read the 'sessionStorage' property from 'Window': Access is denied for this document.
(Session info: chrome=75.0.3770.100)
# #0 0x5651e686d7a9 <unknown>
# /usr/local/bundle/gems/selenium-webdriver-3.142.3/lib/selenium/webdriver/remote/response.rb:72:in `assert_ok'
# /usr/local/bundle/gems/selenium-webdriver-3.142.3/lib/selenium/webdriver/remote/response.rb:34:in `initialize'
# /usr/local/bundle/gems/selenium-webdriver-3.142.3/lib/selenium/webdriver/remote/http/common.rb:88:in `new'
# /usr/local/bundle/gems/selenium-webdriver-3.142.3/lib/selenium/webdriver/remote/http/common.rb:88:in `create_response'
# /usr/local/bundle/gems/selenium-webdriver-3.142.3/lib/selenium/webdriver/remote/http/default.rb:114:in `request'
# /usr/local/bundle/gems/selenium-webdriver-3.142.3/lib/selenium/webdriver/remote/http/common.rb:64:in `call'
# /usr/local/bundle/gems/selenium-webdriver-3.142.3/lib/selenium/webdriver/remote/bridge.rb:167:in `execute'
# /usr/local/bundle/gems/selenium-webdriver-3.142.3/lib/selenium/webdriver/remote/w3c/bridge.rb:567:in `execute'
# /usr/local/bundle/gems/selenium-webdriver-3.142.3/lib/selenium/webdriver/remote/w3c/bridge.rb:305:in `execute_script'
# /usr/local/bundle/gems/selenium-webdriver-3.142.3/lib/selenium/webdriver/remote/w3c/bridge.rb:277:in `clear_session_storage'
# /usr/local/bundle/gems/selenium-webdriver-3.142.3/lib/selenium/webdriver/common/html5/session_storage.rb:40:in `clear'
# /usr/local/bundle/gems/capybara-3.20.0/lib/capybara/selenium/driver.rb:325:in `clear_session_storage'
# /usr/local/bundle/gems/capybara-3.20.0/lib/capybara/selenium/driver.rb:317:in `clear_storage'
# /usr/local/bundle/gems/capybara-3.20.0/lib/capybara/selenium/driver_specializations/chrome_driver.rb:45:in `clear_storage'
# /usr/local/bundle/gems/capybara-3.20.0/lib/capybara/selenium/driver.rb:291:in `clear_browser_state'
# /usr/local/bundle/gems/capybara-3.20.0/lib/capybara/selenium/driver.rb:446:in `reset_browser_state'
# /usr/local/bundle/gems/capybara-3.20.0/lib/capybara/selenium/driver.rb:125:in `reset!'
# /usr/local/bundle/gems/capybara-3.20.0/lib/capybara/selenium/driver_specializations/chrome_driver.rb:36:in `reset!'
# /usr/local/bundle/gems/capybara-3.20.0/lib/capybara/session.rb:128:in `reset!'
# /usr/local/bundle/gems/capybara-3.20.0/lib/capybara.rb:315:in `block in reset_sessions!'
# /usr/local/bundle/gems/capybara-3.20.0/lib/capybara.rb:315:in `reverse_each'
# /usr/local/bundle/gems/capybara-3.20.0/lib/capybara.rb:315:in `reset_sessions!'
# /usr/local/bundle/gems/capybara-3.20.0/lib/capybara/rspec.rb:18:in `block (2 levels) in <top (required)>'
# /usr/local/bundle/gems/rspec-retry-0.6.1/lib/rspec/retry.rb:123:in `block in run'
# /usr/local/bundle/gems/rspec-retry-0.6.1/lib/rspec/retry.rb:110:in `loop'
# /usr/local/bundle/gems/rspec-retry-0.6.1/lib/rspec/retry.rb:110:in `run'
# /usr/local/bundle/gems/rspec-retry-0.6.1/lib/rspec_ext/rspec_ext.rb:12:in `run_with_retry'
# ./spec/rails_helper.rb:224:in `block (2 levels) in <top (required)>'
# /usr/local/bundle/gems/rspec-retry-0.6.1/lib/rspec/retry.rb:123:in `block in run'
# /usr/local/bundle/gems/rspec-retry-0.6.1/lib/rspec/retry.rb:110:in `loop'
# /usr/local/bundle/gems/rspec-retry-0.6.1/lib/rspec/retry.rb:110:in `run'
# /usr/local/bundle/gems/rspec-retry-0.6.1/lib/rspec_ext/rspec_ext.rb:12:in `run_with_retry'
# /usr/local/bundle/gems/rspec-retry-0.6.1/lib/rspec/retry.rb:37:in `block (2 levels) in setup'
Is there anything that I am missing? What is the correct way to setup selenium with docker-compose?
Since you're using the selenium standalone server setup you need to configure the Capybara selenium driver for remote usage.
Capybara.register_driver :selenium_chrome do |app|
options = Selenium::WebDriver::Chrome::Options.new(args: %w[
headless no-sandbox disable-gpu window-size=1920x1080
])
Capybara::Selenium::Driver.new(
app,
browser: :remote,
desired_capabilities: :chrome,
options: options
url: selenium_host,
)
end
Other notes:
If you're using Rails 5.1+ you can probably remove all the database cleaner stuff and just enable transactional tests
Setting ignore_hidden_elements = false is a terrible idea when writing tests since you generally only want to be dealing with elements the user can actually see
:smart is generally a better default for Capybara.match (rather than :prefer_exact) if you care about making sure your tests are referring to the elements you expect them to be.
You shouldn't be including Capybara::DSL in every RSpec test type
You need the hub image which is missing in the above compose file. Link the hub image to node image
selenium-hub:
image: selenium/hub:3.14.0
container_name: hub
ports:
- "4444:4444"
node-chrome:
image: selenium/node-chrome-debug:3.14.0
links:
- selenium-hub
Related
I am trying to setup our Rails project to use rspec. But I am getting 'No examples found' when I run rspec. How can I get rspec to run the example(s)?
I am just using the command rspec with any options or settings.
Rails: 6.0.3.4
Ruby: 2.7.2
My spec file is in the spec/requests folder and has the following content
require 'rails_helper'
RSpec.describe "Posts", type: :request do
describe "GET /index unauthenticated" do
it "returns http 403" do
get "/posts"
expect(response).to have_http_status(403)
end
end
end
My 'spec_helper.rb' is
require File.expand_path("../../config/environment", __FILE__)
require 'byebug'
# This file was generated by the `rails generate rspec:install` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause
# this file to always be loaded, without a need to explicitly require it in any
# files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need
# it.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
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
# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end
# This option will default to `:apply_to_host_groups` in RSpec 4 (and will
# have no way to turn it off -- the option exists only for backwards
# compatibility in RSpec 3). It causes shared context metadata to be
# inherited by the metadata hash of host groups and examples, rather than
# triggering implicit auto-inclusion in groups with matching metadata.
config.shared_context_metadata_behavior = :apply_to_host_groups
# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
=begin
# This allows you to limit a spec run to individual examples or groups
# you care about by tagging them with `:focus` metadata. When nothing
# is tagged with `:focus`, all examples get run. RSpec also provides
# aliases for `it`, `describe`, and `context` that include `:focus`
# metadata: `fit`, `fdescribe` and `fcontext`, respectively.
config.filter_run_when_matching :focus
# Allows RSpec to persist some state between runs in order to support
# the `--only-failures` and `--next-failure` CLI options. We recommend
# you configure your source control system to ignore this file.
config.example_status_persistence_file_path = "spec/examples.txt"
# Limits the available syntax to the non-monkey patched syntax that is
# recommended. For more details, see:
# - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
# - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
# - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
config.disable_monkey_patching!
# Many RSpec users commonly either run the entire suite or an individual
# file, and it's useful to allow more verbose output when running an
# individual spec file.
if config.files_to_run.one?
# Use the documentation formatter for detailed output,
# unless a formatter has already been configured
# (e.g. via a command-line flag).
config.default_formatter = "doc"
end
# Print the 10 slowest examples and example groups at the
# end of the spec run, to help surface which specs are running
# particularly slow.
config.profile_examples = 10
# 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
# Seed global randomization in this process using the `--seed` CLI option.
# Setting this allows you to use `--seed` to deterministically reproduce
# test failures related to randomization by passing the same `--seed` value
# as the one that triggered the failure.
Kernel.srand config.seed
=end
config.expect_with :rspec do |c|
c.syntax = :expect
end
end
Dir["./spec/support/**/*.rb"].each {|f| require f}
My 'rails_helper.rb' file is
# This file is copied to spec/ when you run 'rails generate rspec:install'
require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../config/environment', __dir__)
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
require 'database_cleaner/active_record'
require 'capybara/rspec'
require "shoulda/matchers"
Dir[Rails.root.join('spec', 'support', '**', '*.rb')].each { |f| require f }
# Add additional requires below this line. Rails is not loaded until this point!
# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
#
# The following line is provided for convenience purposes. It has the downside
# of increasing the boot-up time by auto-requiring all files in the support
# directory. Alternatively, in the individual `*_spec.rb` files, manually
# require only the support files necessary.
#
# Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f }
# Checks for pending migrations and applies them before tests are run.
# If you are not using ActiveRecord, you can remove these lines.
begin
ActiveRecord::Migration.maintain_test_schema!
rescue ActiveRecord::PendingMigrationError => e
puts e.to_s.strip
exit 1
end
RSpec.configure do |config|
config.include FactoryBot::Syntax::Methods
config.include Devise::Test::ControllerHelpers, type: :controller
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = false
config.infer_spec_type_from_file_location!
config.filter_rails_from_backtrace!
config.include Devise::Test::ControllerHelpers, type: :controller
config.extend ControllerMacros, type: :controller
config.include RequestSpecHelper, type: :request
config.include FactoryBot::Syntax::Methods
end
Shoulda::Matchers.configure do |config|
config.integrate do |with|
with.test_framework :rspec
with.library :active_record
with.library :active_model
with.library :action_controller
with.library :rails
end
end
RSpec.configure do |config|
config.before(:each) do
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.clean_with(:truncation)
end
config.around(:each) do |example|
DatabaseCleaner.cleaning do
example.run
end
end
end
And my '.rspec' file is
--require spec_helper
I've pushed the complete project code to https://github.com/marksack/rspec-test
EDIT: I did some debugging by stepping through the rspec core code. At some points in the code, I can that it has found the spec files. But it seems to break for some reason when it gets to the point of loading them - perhaps in the load_file_handling_errors method. The invocation of that method passes in the correct file and I don't see any exceptions though.
It seems that you have a cache configuration issue with stimulus_reflex gem when you run the rspec command:
Stimulus Reflex requires caching to be enabled. Caching allows the
session to be modified during ActionCable requests. To enable caching
in development, run:
rails dev:cache
If you know what you are doing and you want to start the application
anyway, you can create a StimulusReflex initializer with the command:
bundle exec rails generate stimulus_reflex:config
Then open your initializer at
<RAILS_ROOT>/config/initializers/stimulus_reflex.rb
and then add the following directive:
StimulusReflex.configure do |config|
config.on_failed_sanity_checks = :warn end
No examples found.
Try replacing this part of config/environments/test.rb:
config.action_controller.perform_caching = false
config.cache_store = :null_store
with:
config.action_controller.perform_caching = true
config.cache_store = :memory_store
Then it should work as expected
I would like to run an RSpec/Capybara test suite in Docker. This test suite performs a file download.
If I run the test suite with rspec, I am able to access the downloaded file.
If I run both rspec and selenium chrome as containers, I cannot figure out how to access the downloaded file.
.ruby-version
2.7.0
Gemfile
source "https://rubygems.org"
gem 'rspec'
gem 'capybara'
gem 'capybara-webmock'
gem 'colorize'
gem 'webdrivers'
#gem 'chromedriver-helper'
gem 'selenium-webdriver'
gem 'byebug'
spec/spec_helper.rb
require 'colorize'
require 'capybara/dsl'
require 'capybara/rspec'
require 'byebug'
RSpec.configure do |config|
config.color = true
config.tty = true
config.formatter = :documentation
config.include Capybara::DSL
end
def create_web_session
Capybara.app_host = 'https://github.com'
Capybara.run_server = false # don't start Rack
if ENV['CHROME_URL']
Capybara.register_driver :selenium_chrome_headless do |app|
args = [
'--no-default-browser-check',
'--start-maximized',
'--headless',
'--disable-dev-shm-usage',
'--whitelisted-ips'
]
caps = Selenium::WebDriver::Remote::Capabilities.chrome("chromeOptions" => {"args" => args})
Capybara::Selenium::Driver.new(
app,
browser: :remote,
desired_capabilities: caps,
url: "http://chrome:4444/wd/hub"
)
end
end
#session = Capybara::Session.new(:selenium_chrome_headless)
##session = Capybara::Session.new(:selenium_chrome)
end
spec/test/demo_spec.rb
require 'spec_helper.rb'
require 'webdrivers/chromedriver'
sleep 1
RSpec.describe 'basic_tests', type: :feature do
before(:each) do
#session = create_web_session
end
it 'Load page' do
#session.visit '/docker/compose/releases/tag/1.27.0'
#session.find_link('Source code (zip)')
#session.click_link('Source code (zip)')
sleep 3
f = File.join('compose-1.27.0.zip')
expect(File.exists?(f)).to be true
File.delete(f)
end
end
Dockerfile
FROM ruby:2.7
RUN gem install bundler
COPY Gemfile Gemfile
COPY Gemfile.lock Gemfile.lock
RUN bundle install
COPY . .
RUN chmod 777 .
CMD ["bundle", "exec", "rspec", "spec"]
docker-compose.yml
version: '3.7'
networks:
mynet:
services:
rspec-chrome:
container_name: rspec-chrome
image: rspec-chrome
build:
context: .
dockerfile: Dockerfile
environment:
CHROME_URL: http://chrome:4444/wd/hub
stdin_open: true
tty: true
networks:
mynet:
depends_on:
- chrome
chrome:
container_name: chrome
image: selenium/standalone-chrome
networks:
mynet:
volumes:
- /dev/shm:/dev/shm
Output when running rspec
basic_tests
Load page
Finished in 8.45 seconds (files took 6.79 seconds to load)
1 example, 0 failures
Output when running docker-compose up -d --build
docker logs -f rspec-chrome
basic_tests
Load page (FAILED - 1)
Failures:
1) basic_tests Load page
Failure/Error: expect(File.exists?(f)).to be true
expected true
got false
# /spec/test/demo_spec.rb:17:in `block (2 levels) in <top (required)>'
When you have Chrome download files they would be downloaded to the Chrome container, so to access them from the container running the tests you probably want to create a shared volume between the two containers and mount it as Chromes download directory.
The following modifications resolved my issue.
spec/spec_helper.rb
Pass the following prefs in chromeOptions
"prefs" => {
'download.default_directory' => '/tmp',
'download.directory_upgrade' => true,
'download.prompt_for_download' => false
}
Here is the complete file
require 'colorize'
require 'capybara/dsl'
require 'capybara/rspec'
require 'byebug'
RSpec.configure do |config|
config.color = true
config.tty = true
config.formatter = :documentation
config.include Capybara::DSL
end
def create_web_session
Capybara.app_host = 'https://github.com'
Capybara.run_server = false # don't start Rack
if ENV['CHROME_URL']
Capybara.register_driver :selenium_chrome_headless do |app|
args = [
'--no-default-browser-check',
'--start-maximized',
'--headless',
'--disable-dev-shm-usage',
'--whitelisted-ips'
]
caps = Selenium::WebDriver::Remote::Capabilities.chrome("chromeOptions" => {
"args" => args,
"prefs" => {
'download.default_directory' => '/tmp',
'download.directory_upgrade' => true,
'download.prompt_for_download' => false
}
})
Capybara::Selenium::Driver.new(
app,
browser: :remote,
desired_capabilities: caps,
url: ENV['CHROME_URL']
)
end
end
#session = Capybara::Session.new(:selenium_chrome_headless)
##session = Capybara::Session.new(:selenium_chrome)
end
spec/test/demo_spec.rb
Change directory to /tmp and look for the download in /tmp
require 'spec_helper.rb'
require 'webdrivers/chromedriver'
sleep 1
RSpec.describe 'basic_tests', type: :feature do
before(:each) do
#session = create_web_session
Dir.chdir "/tmp"
end
it 'Load page' do
#session.visit '/docker/compose/releases/tag/1.27.0'
#session.find_link('Source code (zip)')
#session.click_link('Source code (zip)')
sleep 3
f = File.join('/tmp','compose-1.27.0.zip')
expect(File.exists?(f)).to be true
File.delete(f)
end
end
docker-compose.yml
Share /tmp as a docker volume between the rspec and chrome containers
version: '3.7'
networks:
mynet:
volumes:
downloads:
services:
rspec-chrome:
container_name: rspec-chrome
image: rspec-chrome
build:
context: .
dockerfile: Dockerfile
environment:
CHROME_URL: http://chrome:4444/wd/hub
stdin_open: true
tty: true
networks:
mynet:
depends_on:
- chrome
volumes:
- downloads:/tmp
chrome:
container_name: chrome
image: selenium/standalone-chrome
networks:
mynet:
volumes:
- /dev/shm:/dev/shm
- downloads:/tmp
I'm trying to run rspec tests with Selenium chrome in docker but caught dozens of error. Finally i connected capybara to remote capybara, but now i got these errors:
Got 0 failures and 2 other errors:
1.1) Failure/Error: visit new_user_session_path
Selenium::WebDriver::Error::WebDriverError:
unexpected response, code=404, content-type="text/html"
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Action Controller: Exception caught</title>
....................
Failure/Error: raise Error::WebDriverError, msg
Selenium::WebDriver::Error::WebDriverError:
unexpected response, code=404, content-type="text/html"
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Action Controller: Exception caught</title>
<style>
body {
background-color: #FAFAFA;
...............
So here is my rails_helper.rb. It's really messy cause I tried dozen times with different configs
require 'simplecov'
SimpleCov.start
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'spec_helper'
require 'rspec/rails'
require 'turnip/capybara'
require "selenium/webdriver"
require 'capybara-screenshot/rspec'
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
Shoulda::Matchers.configure do |config|
config.integrate do |with|
with.test_framework :rspec
with.library :rails
end
end
# Checks for pending migration and applies them before tests are run.
# If you are not using ActiveRecord, you can remove this line.
ActiveRecord::Migration.maintain_test_schema!
Capybara::Screenshot.register_driver(:headless_chrome) do |driver, path|
driver.browser.manage.window.resize_to(1600, 1200)
driver.browser.save_screenshot("tmp/capybara/chrom_#{Time.now}.png")
end
url = 'http://test.prs.com:3001/'
Capybara.javascript_driver = :remote_browser
Capybara.register_driver :headless_chrome do |app|
capabilities = Selenium::WebDriver::Remote::Capabilities.chrome(
chromeOqptions: { args: %w(headless disable-gpu no-sandbox) }
)
end
capabilities = Selenium::WebDriver::Remote::Capabilities.chrome(
chromeOqptions: { args: %w(headless disable-gpu no-sandbox) }
)
Capybara.default_driver = :remote_browser
Capybara.register_driver :remote_browser do |app|
Capybara::Selenium::Driver.new(app, :browser => :remote, url: url,
desired_capabilities: capabilities)
end
# Capybara::Selenium::Driver.new app,
# browser: :chrome,
# desired_capabilities: capabilities
# end
Capybara.app_host = "http://#{ENV['APP_HOST']}:#{3001}"
Capybara.run_server = false
Capybara.configure do |config|
config.always_include_port = true
end
Chromedriver.set_version '2.32'
# Capybara.javascript_driver = :headless_chrome
# Capybara.server_host= '0.0.0.0'
# Capybara.default_host = "http://test.prs.com"
# Capybara.app_host = "#{Capybara.default_host}:#{Capybara.server_port}"
RSpec.configure do |config|
config.include FactoryGirl::Syntax::Methods
config.include RequestSpecHelper
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.before(:each) do
DatabaseCleaner.strategy = :truncation
DatabaseCleaner.clean
end
config.before(:all, type: :request) do
host! 'test.prs.com'
end
config.use_transactional_fixtures = true
config.infer_spec_type_from_file_location!
config.filter_rails_from_backtrace!
end
And here is my docker-compose.yml:
version: '3'
services:
db:
image: postgres
web:
build: .
command: bundle exec rails s -p 3001 -b '0.0.0.0'
volumes:
- .:/prs
ports: ['3000:3000', '3001:3001']
# - "3001:3001"
depends_on:
- db
- selenium
extra_hosts:
- "test.prs.com:127.0.0.1"
environment:
- APP_HOST=test.prs.com
links:
- selenium
selenium:
image: selenium/standalone-chrome-debug:3.6.0-bromine
# Debug version enables VNC ability
ports: ['4444:4444', '5900:5900']
# Bind selenium port & VNC port
volumes:
- /dev/shm:/dev/shm
shm_size: 1024m
privileged: true
container_name: selenium
I'm new to all this so any help will be appreciated.
From the comments you have clarified that you are trying to run the tests in the web docker instance while using the selenium driven browser in the selenium docker instance. Additionally, since your tests are working locally I assume you are using Rails 5.1+ so transactional testing for feature tests will work. Based on those parameters there are a few things needed to make everything work properly.
Capybara needs to start its own copy of the app to run the tests against. This is needed for transactional testing to work and for request completion detection. You enable that with
Capybara.run_server = true # You currently have this set to false for some reason
Capybara needs to run its copy of the app on an interface which can be reached from the selenium docker instance. Easiest way to do that is to specify to bind to 0.0.0.0
Capybara.server_host = `0.0.0.0`
Capybara.server_port = 3001 # I'm assuming this is what you want, change to another port and make sure it's reachable from `selenium` instance if desired
The driver capybara is using needs to be configured to use the selenium instance
Capybara.register_driver :remote_browser do |app|
capabilities = Selenium::WebDriver::Remote::Capabilities.chrome(
chromeOptions: { args: %w(headless disable-gpu no-sandbox) }
)
Capybara::Selenium::Driver.new(app,
:browser => :remote,
url: "http://selenium:4444",
desired_capabilities: capabilities
)
end
Capybara.javascript_driver = :remote_browser
# Capybara.default_driver = :remote_browser # only needed if you want all tests to use selenium rather than just JS tagged tests.
Configure Capybara to use the correct host when visiting relative URLs
Capybara.app_host = "http://web:3001" # a URL that represents the `web` docker instance from the perspective of the `selenium` docker instance
Notes: If you were expecting your tests to run on port 3001 as I guessed, then you want to stop the docker instance from launching rails s on that port, since you want the tests run against an app instance that Capybara itself launches # command: bundle exec rails s -p 3001 -b '0.0.0.0'. If the instance you currently have running on 3001 is for something else then you'll need a different port for the tests.
Additionally, if you're not running Rails 5.1+ then you'll need to set config.use_transactional_fixtures = false and fully configure database_cleaner - https://github.com/DatabaseCleaner/database_cleaner#rspec-with-capybara-example . If you are using Rails 5.1+ then you can probably remove all the database_cleaner stuff.
My problem was completely unrelated to Docker, Selenium, Capybara, Chromedriver or any of that. They were all red herrings because on my container only tests related to feature specs were failing.
It turns out they were all failing because feature specs are the only part of the app that looks at IP addresses.
I am using the ip_anonymizer gem and failed to set the IP_HASH_SECRET for the container. Hopefully, anyone else using this gem with Capybara and CI finds this useful.
I'm using Rails (5.1.0), Mongoid(6.1.0) and Rspec(3.6.0). I have removed active record from my app. Everything is working perfectly apart from tests. When I'm running rspec i get error:
Failure/Error: raise ConnectionNotEstablished, "No connection pool with '#{spec_name}' found." unless pool
ActiveRecord::ConnectionNotEstablished:
No connection pool with 'primary' found.
# /Users/kukicola/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.0/lib/active_record/connection_adapters/abstract/connection_pool.rb:930:in `retrieve_connection'
# /Users/kukicola/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.0/lib/active_record/connection_handling.rb:116:in `retrieve_connection'
# /Users/kukicola/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.0/lib/active_record/connection_handling.rb:88:in `connection'
# /Users/kukicola/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.0/lib/active_record/fixtures.rb:516:in `create_fixtures'
# /Users/kukicola/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.0/lib/active_record/fixtures.rb:1028:in `load_fixtures'
# /Users/kukicola/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.0/lib/active_record/fixtures.rb:999:in `setup_fixtures'
# /Users/kukicola/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.0/lib/active_record/fixtures.rb:851:in `before_setup'
# /Users/kukicola/.rvm/gems/ruby-2.4.1/gems/rspec-rails-3.6.0/lib/rspec/rails/adapters.rb:126:in `block (2 levels) in <module:MinitestLifecycleAdapter>'
# /Users/kukicola/.rvm/gems/ruby-2.4.1/gems/rspec-core-3.6.0/lib/rspec/core/example.rb:447:in `instance_exec'
# /Users/kukicola/.rvm/gems/ruby-2.4.1/gems/rspec-core-3.6.0/lib/rspec/core/example.rb:447:in `instance_exec'
# /Users/kukicola/.rvm/gems/ruby-2.4.1/gems/rspec-core-3.6.0/lib/rspec/core/hooks.rb:375:in `execute_with'
# /Users/kukicola/.rvm/gems/ruby-2.4.1/gems/rspec-core-3.6.0/lib/rspec/core/hooks.rb:606:in `block (2 levels) in run_around_example_hooks_for'
# /Users/kukicola/.rvm/gems/ruby-2.4.1/gems/rspec-core-3.6.0/lib/rspec/core/example.rb:342:in `call'
# /Users/kukicola/.rvm/gems/ruby-2.4.1/gems/rspec-core-3.6.0/lib/rspec/core/hooks.rb:607:in `run_around_example_hooks_for'
# /Users/kukicola/.rvm/gems/ruby-2.4.1/gems/rspec-core-3.6.0/lib/rspec/core/hooks.rb:464:in `run'
# /Users/kukicola/.rvm/gems/ruby-2.4.1/gems/rspec-core-3.6.0/lib/rspec/core/example.rb:457:in `with_around_example_hooks'
# /Users/kukicola/.rvm/gems/ruby-2.4.1/gems/rspec-core-3.6.0/lib/rspec/core/example.rb:500:in `with_around_and_singleton_context_hooks'
# /Users/kukicola/.rvm/gems/ruby-2.4.1/gems/rspec-core-3.6.0/lib/rspec/core/example.rb:251:in `run'
# /Users/kukicola/.rvm/gems/ruby-2.4.1/gems/rspec-core-3.6.0/lib/rspec/core/example_group.rb:627:in `block in run_examples'
# /Users/kukicola/.rvm/gems/ruby-2.4.1/gems/rspec-core-3.6.0/lib/rspec/core/example_group.rb:623:in `map'
# /Users/kukicola/.rvm/gems/ruby-2.4.1/gems/rspec-core-3.6.0/lib/rspec/core/example_group.rb:623:in `run_examples'
# /Users/kukicola/.rvm/gems/ruby-2.4.1/gems/rspec-core-3.6.0/lib/rspec/core/example_group.rb:589:in `run'
# /Users/kukicola/.rvm/gems/ruby-2.4.1/gems/rspec-core-3.6.0/lib/rspec/core/example_group.rb:590:in `block in run'
# /Users/kukicola/.rvm/gems/ruby-2.4.1/gems/rspec-core-3.6.0/lib/rspec/core/example_group.rb:590:in `map'
# /Users/kukicola/.rvm/gems/ruby-2.4.1/gems/rspec-core-3.6.0/lib/rspec/core/example_group.rb:590:in `run'
# /Users/kukicola/.rvm/gems/ruby-2.4.1/gems/rspec-core-3.6.0/lib/rspec/core/runner.rb:118:in `block (3 levels) in run_specs'
# /Users/kukicola/.rvm/gems/ruby-2.4.1/gems/rspec-core-3.6.0/lib/rspec/core/runner.rb:118:in `map'
# /Users/kukicola/.rvm/gems/ruby-2.4.1/gems/rspec-core-3.6.0/lib/rspec/core/runner.rb:118:in `block (2 levels) in run_specs'
# /Users/kukicola/.rvm/gems/ruby-2.4.1/gems/rspec-core-3.6.0/lib/rspec/core/configuration.rb:1894:in `with_suite_hooks'
# /Users/kukicola/.rvm/gems/ruby-2.4.1/gems/rspec-core-3.6.0/lib/rspec/core/runner.rb:113:in `block in run_specs'
# /Users/kukicola/.rvm/gems/ruby-2.4.1/gems/rspec-core-3.6.0/lib/rspec/core/reporter.rb:79:in `report'
# /Users/kukicola/.rvm/gems/ruby-2.4.1/gems/rspec-core-3.6.0/lib/rspec/core/runner.rb:112:in `run_specs'
# /Users/kukicola/.rvm/gems/ruby-2.4.1/gems/rspec-core-3.6.0/lib/rspec/core/runner.rb:87:in `run'
# /Users/kukicola/.rvm/gems/ruby-2.4.1/gems/rspec-core-3.6.0/lib/rspec/core/runner.rb:71:in `run'
# /Users/kukicola/.rvm/gems/ruby-2.4.1/gems/rspec-core-3.6.0/lib/rspec/core/runner.rb:45:in `invoke'
# /Users/kukicola/.rvm/gems/ruby-2.4.1/gems/rspec-core-3.6.0/exe/rspec:4:in `<top (required)>'
# /Users/kukicola/.rvm/gems/ruby-2.4.1/bin/rspec:23:in `load'
# /Users/kukicola/.rvm/gems/ruby-2.4.1/bin/rspec:23:in `<main>'
# /Users/kukicola/.rvm/gems/ruby-2.4.1/bin/ruby_executable_hooks:15:in `eval'
# /Users/kukicola/.rvm/gems/ruby-2.4.1/bin/ruby_executable_hooks:15:in `<main>'
#
# Showing full backtrace because every line was filtered out.
# See docs for RSpec::Configuration#backtrace_exclusion_patterns and
# RSpec::Configuration#backtrace_inclusion_patterns for more information.
My rails_helper.rb file:
# This file is copied to spec/ when you run 'rails generate rspec:install'
require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
Mongoid.load!(Rails.root.join("config", "mongoid.yml"))
# Add additional requires below this line. Rails is not loaded until this point!
# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
#
# The following line is provided for convenience purposes. It has the downside
# of increasing the boot-up time by auto-requiring all files in the support
# directory. Alternatively, in the individual `*_spec.rb` files, manually
# require only the support files necessary.
#
# Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
# Checks for pending migration and applies them before tests are run.
# If you are not using ActiveRecord, you can remove this line.
#ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
#config.fixture_path = "#{::Rails.root}/spec/fixtures"
# 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
# RSpec Rails can automatically mix in different behaviours to your tests
# based on their file location, for example enabling you to call `get` and
# `post` in specs under `spec/controllers`.
#
# You can disable this behaviour by removing the line below, and instead
# explicitly tag your specs with their type, e.g.:
#
# RSpec.describe UsersController, :type => :controller do
# # ...
# end
#
# The different available types are documented in the features, such as in
# https://relishapp.com/rspec/rspec-rails/docs
config.infer_spec_type_from_file_location!
# Filter lines from Rails gems in backtraces.
config.filter_rails_from_backtrace!
# arbitrary gems may also be filtered via:
# config.filter_gems_from_backtrace("gem name")
# config.before(:suite) do
# DatabaseCleaner.clean_with(:truncation)
# end
#
# config.before(:each) do
# DatabaseCleaner.strategy = :truncation
# end
#
# config.before(:each, :js => true) do
# DatabaseCleaner.strategy = :truncation
# end
#
# config.before(:each) do
# DatabaseCleaner.start
# end
#
# config.after(:each) do
# DatabaseCleaner.clean
# end
end
And spec_helper.rb:
# This file was generated by the `rails generate rspec:install` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause
# this file to always be loaded, without a need to explicitly require it in any
# files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need
# it.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
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
# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end
# This option will default to `:apply_to_host_groups` in RSpec 4 (and will
# have no way to turn it off -- the option exists only for backwards
# compatibility in RSpec 3). It causes shared context metadata to be
# inherited by the metadata hash of host groups and examples, rather than
# triggering implicit auto-inclusion in groups with matching metadata.
config.shared_context_metadata_behavior = :apply_to_host_groups
# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
=begin
# This allows you to limit a spec run to individual examples or groups
# you care about by tagging them with `:focus` metadata. When nothing
# is tagged with `:focus`, all examples get run. RSpec also provides
# aliases for `it`, `describe`, and `context` that include `:focus`
# metadata: `fit`, `fdescribe` and `fcontext`, respectively.
config.filter_run_when_matching :focus
# Allows RSpec to persist some state between runs in order to support
# the `--only-failures` and `--next-failure` CLI options. We recommend
# you configure your source control system to ignore this file.
config.example_status_persistence_file_path = "spec/examples.txt"
# Limits the available syntax to the non-monkey patched syntax that is
# recommended. For more details, see:
# - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
# - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
# - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
config.disable_monkey_patching!
# Many RSpec users commonly either run the entire suite or an individual
# file, and it's useful to allow more verbose output when running an
# individual spec file.
if config.files_to_run.one?
# Use the documentation formatter for detailed output,
# unless a formatter has already been configured
# (e.g. via a command-line flag).
config.default_formatter = "doc"
end
# Print the 10 slowest examples and example groups at the
# end of the spec run, to help surface which specs are running
# particularly slow.
config.profile_examples = 10
# 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
# Seed global randomization in this process using the `--seed` CLI option.
# Setting this allows you to use `--seed` to deterministically reproduce
# test failures related to randomization by passing the same `--seed` value
# as the one that triggered the failure.
Kernel.srand config.seed
=end
end
Problem solved - I had bad carrier_wave config which was loading active record
Here's a line from my test.rb environnment file in a Rails 3.1.12 app:
config.action_mailer.default_url_options = config.action_controller.default_url_options = { :host => "127.0.0.1", :port => 3000 }
Now here's the test I make:
subject { get :success }
subject.should redirect_to(:home)
This produces an error:
Failure/Error: subject.should redirect_to(:home)
Expected response to be a redirect to <http://127.0.0.1:3000/> but was a redirect to <http://test.host/>
What did I do wrong? Or else, where the testing host be configured?
Here's the spec_helper.rb file for complete reference.
# 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}
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
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
# 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
Capybara.configure do |config|
config.app_host = 'http://127.0.0.1'
config.server_port = 3000
end
This worked for me:
# spec/controllers/whatever_controller_spec.rb
before :each do
#request.host = '127.0.0.1:3000'
end
Based on the link #dan-reedy supplied. It is sublimely annoying to have to configure the exact same parameters in config/environments, spec/spec_helper.rb and again here... all in marginally different ways (with 'http://' or without, with port number or port specified separately). Even Capybara.configure syntax can't seem to stay consistent to itself between versions...
But give it a try and see if that solves it.
Here's the workaround that seems to have fixed the issue for me:
In spec/rails_helper.rb add this
module ActionDispatch
class TestRequest
# Override host, by default it is test.host
def host
'localhost:3000'
end
end
end
To set the app host and server port with Capybara add the following lines to your spec/spec_helper.rb file
Capybara.configure do |config|
config.app_host = 'http://127.0.0.1'
config.server_port = 3000
end
-- Edit #1
A nice overview of testing domains is available at http://blog.joncairns.com/2012/12/testing-domains-with-rails-and-test-unit/