I'm very new to Capybara and have also never used Selenium before. I'm doing a ruby on rails project on MacOSX and for whatever reason, a browser window never opens when I run my test.
My stack is: Capybara, Selenium, Rspec, Ruby on Rails.
My test is as follows:
describe 'Downloads', js: true do
context ' compress zip and download file' do
before do
Capybara.current_driver = :selenium
session = Capybara::Session.new(:selenium)
session.visit '/users/sign_in'
find('#tab_signin').click
within("#new_user") do
fill_in 'user_login', :with => 'admin#local.host'
fill_in 'user_password', :with => 'password'
end
click_button 'Sign in'
end
it 'downloads the project and navigates to downloads page' do
visit 'some/path'
within '.create-download' do
find(:select).find("option[value='zip']").select_option
end
sleep 3
page.should have_css('#download-modal.in')
end
end
end
I've also tried to change stuff in my features/support/env.rb to be this:
Capybara.javascript_driver = :selenium
Capybara.register_driver :selenium do |app|
profile = Selenium::WebDriver::Firefox::Profile.new
Capybara::Selenium::Driver.new(app, :browser => :firefox, :profile => profile)
end
Update
Not only is the browser not opening, but the test is failing with the following output:
Failure/Error: visit '/users/sign_in'
ArgumentError:
unknown option: {:resynchronize=>true}
So after a lot of work I finally figured it out. Thanks to #RAJ for the suggestion of where to put that config info. The feature/support/env.rb is for cucumber and I'm using rspec.
Most of the articles I read about selenium and capybara told me to use the js: true option at the start of the block, but that didn't work. Once I changed that to feature: true it worked. My final solution looks like this:
describe 'Downloads', feature: true do
context 'compress zip and download file' do
before do
visit '/users/sign_in'
find("a[href$='signin']").click
within("#new_user") do
fill_in 'user_login', :with => 'admin#local.host'
fill_in 'user_password', :with => 'password'
end
click_button 'Sign in'
end
it 'downloads the project and navigates to downloads page' do
visit 'some/path'
within '.create-download' do
find(:select).find("option[value='zip']").select_option
end
sleep 3
page.should have_css('#download-modal.in')
end
end
end
Then my spec_helper.rb looks like:
Capybara.register_driver :selenium do |app|
profile = Selenium::WebDriver::Firefox::Profile.new
Capybara::Selenium::Driver.new( app, :profile => profile)
end
Capybara.default_wait_time = 10
Capybara.current_driver = :selenium
Capybara.app_host = 'http://localhost:3000'
Another thing that I did and I wasn't aware before was install the Selenium IDE on Firefox. Since I'd never used Selenium before, I thought all I needed was the gem.
Related
I'm using Capybara, the selenium-webdriver gem, and chromedriver in order to drive my javascript enabled tests.
The problem is that about 50% of our builds fail due to a Net::ReadTimeout error. At first this was manifesting as a 'could not find element' error, but after I upped Capybara's default max wait time to 30 seconds, I started seeing the timeout.
I examined the screenshots of when the timeout happens, it's stuck on a 'Successfully logged in' modal that we show briefly before using the Javascript function, location.reload(), to reload the page.
I've ran the test locally and can sometimes reproduce it, also randomly. Sometimes it zips by this modal and does the reload so fast you can barely see it, and other times it just hangs forever.
I don't feel like it's an asset compilation issue, since the site has already loaded at that point in order for the user to access the login form.
Wondering if anyone has seen this before and knows a solution.
The specific code:
visit login_path
page.within '#sign-in-pane__body' do
fill_in 'Email', with: user.email
click_button 'Submit'
end
expect(page).to have_content 'Enter Password'
page.within '#sign-in-pane__body' do
fill_in 'Password', with: user.password
click_button 'Submit'
end
expect(page).to have_text 'Home page landing text'
The hang up happens between click_button 'Submit' and expecting the home page text.
The flow of the logic causing the timeout is the user submits the login form, we wait for the server to render a .js.erb template that triggers a JS event upon successful login. When that trigger happens we show a modal saying that login was successful, then execute a location.reload().
It turned out this wasn't exclusive to doing a location.reload() in JS. It sometimes happened just visiting a page.
The solution for me was to create an HTTP client for the selenium driver and specify a longer timeout:
Capybara.register_driver :chrome do |app|
client = Selenium::WebDriver::Remote::Http::Default.new
client.read_timeout = 120
Capybara::Selenium::Driver.new(app, {browser: :chrome, http_client: client})
end
Solved similar problem by using my own version of visit method:
def safe_visit(url)
max_retries = 3
times_retried = 0
begin
visit url
rescue Net::ReadTimeout => error
if times_retried < max_retries
times_retried += 1
puts "Failed to visit #{url}, retry #{times_retried}/#{max_retries}"
retry
else
puts error.message
puts error.backtrace.inspect
exit(1)
end
end
end
Here is what you need to do if you need to configure it for headless chrome
Capybara.register_driver :headless_chrome do |app|
client = Selenium::WebDriver::Remote::Http::Default.new
client.timeout = 120 # instead of the default 60
options = Selenium::WebDriver::Chrome::Options.new
options.headless!
Capybara::Selenium::Driver.new(app, {
browser: :chrome,
http_client: client,
options: options
})
end
Capybara.default_driver = :headless_chrome
Capybara.javascript_driver = :headless_chrome
Passing headless argument in capabilities was not working for me.
capabilities = Selenium::WebDriver::Remote::Capabilities.chrome(
chromeOptions: { args: %w[headless disable-gpu] }
)
Here is more details about why headless in capabilities was not working.
I'm using RSpec + capybara, and the capybara-webkit as driver.
I have to check if a JS box exists in the page after clicking on a button, but with no results.
If I use selenium as a driver, the test passes, but I need to use capybara-webkit.
I'm using
expect(page).to have_selector(#js_window)
My configuration is
Capybara.run_server = false
Capybara.default_selector = :css
Capybara.default_max_wait_time = 1
Capybara.javascript_driver = :webkit
RSpec.configure do |config|
config.include Capybara::DSL
end
In the end, it was a problem with my config.block_unknown_urls (I was blocking the url I needed) and the default_max_wait_time (I changed it from 1 to 3).
Solved now!
I've got got a page with some AJAX code that I'm trying to build a spec for using Capybara. This test works:
context 'from the JobSpec#index page' do
scenario 'clicks the Run now link' do
visit job_specs_path
within( find('tr', text: #job_spec.name) ) { click_link 'run_now' }
visit current_path
expect(find('tr', text: #job_spec.name)).to have_content(/(running|success)/)
end
end
After clicking the link 'run_now', a job is launched and the user is redirected to the launched_jobs_path, which has a Datatable that uses some AJAX to pull currently running jobs. This test passes. However, I wanted to add to the test to check to make sure that the job wasn't already running before clicking the 'run_now' button (which would give me a false positive). I started playing around with it, but then I noticed that even simply putting visit launched_jobs_path before visit job_specs_path would cause the test to fail with the error
Failure/Error: expect(find('tr', text: #job_spec.name)).to have_content(/(running|success)/)
Capybara::ElementNotFound:
Unable to find css "tr" with text "job_spec_collection-1"
I'm fairly certain that this is an issue with the Javascript not running at the right time, but I don't quite know how to resolve it. Any ideas? This is Rails 4.1 with Capybara 2.4, and Capybara-webkit 1.3.
Thanks!
Update
In the parent context of the spec, I do have :js => true
feature 'User runs a JobSpec now', :js => true do
before do
Capybara.current_driver = :webkit
#job_spec = FactoryGirl.create(:job_spec, :with_client_spaces)
end
after { Capybara.use_default_driver }
context 'from the JobSpec#index page' do
...
end
end
I think it might be as simple as adding :js => true to your scenario header so that it knows to launch webkit / selenium to test the js / ajax.
scenario 'clicks the Run now link', :js => true do
Hope that helps!
UPDATE
Well here's one more idea. You could try adding this to your 'rails_helper' or 'spec_helper' file to set the :js driver.
Capybara.javascript_driver = :webkit
Do you have other :js tests that are working properly with :webkit? Have you tried using save_and_open_page to see if the element you are looking for is actually on the page and Capybara just isn't finding it?
Ok, pretty sure I've got something that will at least work for now. If anyone has more elegant solutions I'd love to hear them.
I think the issue is in the complexity of what happens in the 'run_now' controller. It adds a job to a Rufus scheduler process, which then has to start the job (supposed to start immediately). Only after the launched job is running via Rufus does an entry in the launched_jobs table get created.
While developing, I would see the job just launched as soon as I clicked 'Run now'. However, I'm guessing that WebKit is so fast that the job hasn't been launched by the time it gets to the launched_jobs#index page. The extra visit current_path there seem to help at first because it would refresh the page, but it only worked occasionally. Wrapping these last two steps in a synchronize block seems to work reliably (I've run it about 20 times now without any failures):
context 'from the JobSpec#index page' do
scenario 'clicks the Run now link' do
# First make sure that the job isn't already running
visit launched_jobs_path
expect(page).to have_no_selector('tr', text: #job_spec.name)
# Now launch the job
visit job_specs_path
within( find('tr', text: #job_spec.name) ) { click_link 'run_now' }
page.document.synchronize do
visit current_path
expect(find('tr', text: #job_spec.name)).to have_content(/(running|success)/)
end
end
end
currently I am facing to a problem that: we need to control the linux scripts running in background from web page. e.g. we could start/stop a 'script' via the button on the webpage.
also another good example is:
I am an expert of web development, and very familiar with javascript(setTimeout to refresh the progress), ruby on rails.
thanks a lot.
if it is linux systems then you could use
system(path_to_script.sh)
or
`path_to_script.sh`
in your controller
thanks to #xvidun, I found the solution: using god.
the key process is: how to make a non-daemon process start as a daemon. "nohup ... &" doesn't work for me. so I tried god and it is great!
in my case, the process I want to run is:
$ cd /sg552/workspace/m-video-fetcher
$ nohup ruby script/start_fetch.rb &
here is how I did the job:
step1 : create a god config file:
# file name: fetcher.god
RAILS_ROOT = '/sg552/workspace/m-video-fetcher'
God.watch do |w|
w.name = 'fetcher'
w.dir = RAILS_ROOT
w.start = "ruby script/start_fetch.rb"
w.log = "#{RAILS_ROOT}/fetcher_stdout.log"
w.keepalive
end
step2:
$ god start -c fetcher.god
step3:
# in the view, give users the interface to restart this job.
<a href='/settings/restart_fetch_for_all_plans'>restart</A>
# in the controller:
def restart_fetch_for_all_plans
result = `god stop fetcher && god start fetcher`
redirect_to :back, :notice => "fetcher restarted, #{result}"
end
I'm new to Capybara and testing on Rails in general, so please forgive me if this is a simple answer.
I've got this test
it "should be able to edit an assignment" do
visit dashboard_path
select(#project.client + " - " + #project.name, :from => "assignment_project_id")
select(#team_member.first_name + " " + #team_member.last_name, :from => "assignment_person_id")
click_button "Create assignment"
page.should have_content(#team_member.first_name)
end
it passes as is, but if I add :js => true it fails with
cannot select option, no option with text 'Test client - Test project' in select box 'assignment_project_id'
I'm using FactoryGirl to create the data, and as the test passes without JS, I know that part is working.
I've tried with the default JS driver, and with the :webkit driver (with capybara-webkit installed)
I guess I don't understand enough what turning on JS for Capybara is doing.
Why would the test fail with JS on?
I've read the Capybara readme at https://github.com/jnicklas/capybara and it solved my issue.
Transactional fixtures only work in the default Rack::Test driver, but
not for other drivers like Selenium. Cucumber takes care of this
automatically, but with Test::Unit or RSpec, you may have to use the
database_cleaner gem. See this explanation (and code for solution 2
and solution 3) for details.
But basically its a threading issue that involves Capybara having its own thread when running the non-Rack driver, that makes the transactional fixtures feature to use a second connection in another context. So the driver thread is never in the same context of the running rspec.
Luckily this can be easily solve (at least it solved for me) doing a dynamic switching in th DatabaseCleaner strategy to use:
RSpec.configure do |config|
config.use_transactional_fixtures = false
config.before :each do
if Capybara.current_driver == :rack_test
DatabaseCleaner.strategy = :transaction
else
DatabaseCleaner.strategy = :truncation
end
DatabaseCleaner.start
end
config.after do
DatabaseCleaner.clean
end
end
A variation of brutuscat's answer that fixed our feature specs (which all use Capybara):
config.before(:suite) do
DatabaseCleaner.clean_with(:truncation)
end
config.before(:each) do
# set the default
DatabaseCleaner.strategy = :transaction
end
config.before(:each, type: :feature) do
DatabaseCleaner.strategy = :truncation
end
config.before(:each) do
DatabaseCleaner.start
end
config.append_after(:each) do
DatabaseCleaner.clean
end
There is another way to deal with this problem now described and discussed here: Why not use shared ActiveRecord connections for Rspec + Selenium?