I summarized how to build an RSpec test environment in the docker development environment. Since I am a beginner and self-taught, I think there are some mistakes and better ways to do it, but I would be grateful if you could point out at that time.
I referred to the following article. I tried RSpec System test with Selenium Docker on Rails on Docker.
Previously, I posted an article about browser test error resolution in Cannot run browser test in Rails development using Docker. If you comment and use docker-compose to run chrome itself as one of the services, I was advised that it would be easy to test without polluting the Rails environment, so I tried it. Thank you for pointing out!
The image used is standalone-chrome, which is the one with Chrome installed from the beginning.
docker-compose.yml
version: '3'
services:
web:
build: .
command: bundle exec rails s -p 3000 -b '0.0.0.0'
volumes:
- .:/[app name]
ports:
- 3000:3000
depends_on:
- db
- chrome #← Add
tty: true
stdin_open: true
db:
image: mysql:5.7
volumes:
- db-volume:/var/lib/mysql
environment:
MYSQL_ROOT_PASSWORD: password
#↓ Add
chrome:
image: selenium/standalone-chrome:latest
ports:
- 4444:4444
#↑ Add
volumes:
db-volume:
Add gem of rspec-rails
Gemfile
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
gem 'rspec-rails', '~> 4.0.1' #add to
gem 'factory_bot_rails', '~>4.11'
end
Install gem.
$ docker-compose build
Install RSpec
$ docker-compose run web rails g rspec:install
Next, in the file created by installation, describe the settings in "rails_helper.rb". Set to use docker-selenium container browser when running RSpec.
/spec/rails_helper.rb
#~
Capybara.register_driver :remote_chrome do |app|
url = "http://chrome:4444/wd/hub"
caps = ::Selenium::WebDriver::Remote::Capabilities.chrome(
"goog:chromeOptions" => {
"args" => [
"no-sandbox",
"headless",
"disable-gpu",
"window-size=1680,1050"
]
}
)
Capybara::Selenium::Driver.new(app, browser: :remote, url: url, desired_capabilities: caps)
end
#~
RSpec.configure do |config|
config.before(:each, type: :system) do
driven_by :rack_test
end
config.before(:each, type: :system, js: true) do
driven_by :remote_chrome
Capybara.server_host = IPSocket.getaddress(Socket.gethostname)
Capybara.server_port = 4444
Capybara.app_host = "http://#{Capybara.server_host}:#{Capybara.server_port}"
end
#~
end
Finally, edit .rspec
to read the settings in rails_helper.rb.
.rspec
- --require spec_helper
+ --require rails_helper
that's all.
Now let's write a test and see if we can run it.
#When the container starts
$ docker-compose exec web rspec [rspec test file path]
I was able to see a hard copy of my browser when the test failed.
Recommended Posts