# spec/support/capybara.rb
require 'capybara/rails'
require 'capybara/rspec'
# port and url to webpack server
WEB_TEST_PORT = '5005'.freeze
WEB_TEST_URL = "http://localhost:#{WEB_TEST_PORT}".freeze
def capybara_wait_for_webpack_server
10.times.each do |_|
begin
Net::HTTP.get(URI(WEB_TEST_URL))
return
rescue Errno::ECONNREFUSED
sleep 1
end
end
end
# https://github.com/thoughtbot/capybara-webkit#configuration
Capybara::Webkit.configure do |config|
config.raise_javascript_errors = true
end
# https://github.com/teamcapybara/capybara/blob/master/lib/capybara.rb#L35
Capybara.configure do |config|
# server puntastic will run the webpack server and the rails server
config.register_server :puntastic do |app, port, host|
# run webpack server using childprocess gem
process = ChildProcess.build('yarn', 'start')
# process.io.inherit! # uncomment for debugging
process.environment['WEB_PORT'] = WEB_TEST_PORT
process.environment['API_URL'] = "#{host}:#{port}"
process.cwd = Rails.root.join('web')
process.leader = true
process.detach = true
begin
Net::HTTP.get(URI(WEB_TEST_URL))
rescue
process.start
at_exit { process.stop unless process.exited? }
capybara_wait_for_webpack_server
end
# run the Rails API server
options = { Host: host, Port: port, Threads: "0:4", Silent: true }
Rack::Handler::Puma.run(app, options)
end
# use a javascript driver
config.default_driver = :webkit
config.javascript_driver = :webkit
# use the custom server
config.server = :puntastic
config.run_server = true
config.app_host = WEB_TEST_URL
end