Capybara and Ajax request on document ready - ruby-on-rails

So I have script on page:
$(document).ready ->
$.rails.ajax
type: 'POST'
url: url
data:
request:
'some data': data
success: (response) ->
do something
And I have feature test:
RSpec.describe 'some test', type: :feature, js: true do
it 'tests' do
visit '/'
page.select 'some value', from: 'id'
click_on('Some button')
expect(page).to have_content 'some text'
end
Also some config:
Capybara.register_driver :chrome do |app|
Capybara::Selenium::Driver.new(app, browser: :chrome)
end
Capybara.javascript_driver = :chrome
How to make capybara run those script that should run on document ready? It seems that id doesn't run now.

There is no need to tell Capybara to run a script in the page. If the script is in the page then Chrome will run it (assuming no JS errors, etc).
Since you don't indicate which line the test fails on, or what the exact failure message is, it's tough to tell exactly what the ajax request is loading to the page and whether you're expecting that code to run on the page returned by visit '/' or on the page directed to by clicking on the button. If the former then you need to have an expectation for whatever visible change to the page happens when the ajax request succeeds. If the latter then most likely you just have Capybara.default_max_wait_time set too low for the hardware you're testing on (increase it to 5 or 10).

Related

Erratic behavior of Vue.js application in test mode (rspec)

I have a Rails 6 application which I test with rspec, Capybara and Chrome headless on a remote VM. With the new webdrivers gem, not that ancient poltergeist thing.
It has an user manager mini-app written in Vue 2.something that behaves in some stupefying ways:
Excerpt from Vue application
{
el: "#app",
data: {
initial_load_completed: false,
users: []
},
created: function(){
this.loadUsers();
},
methods: {
loadUsers: function(){ /* straightforward JSON load from server into .users and set .initial_load_completed to true */ }
/* lots of other code */
},
computed: {
hasUsers: function(){
return this.users.length > 0;
}
/* lots of other code */
}
}
View excerpt
<div id="app">
<!-- loads of other code -->
<div v-if="!initial_load_completed && !hasUsers">Loading your users, please wait...</div>
<div v-if="initial_load_completed && !hasUsers">There are no users for your account right now...</div>
<!-- lots of other code -->
</div>
The application works perfectly in prod and dev, on chrome, safari, tablets, iphones, even on my 3 year old smart TV Trashroid, even on IE. But under rspec tests it does things such as this:
This example with those 2 divs showing/hiding based on users loaded is just a small thing that's wrong in this picture, many other controls were supposed to not show with an empty users array. And this is a happy happy joy joy case, about 50% of example runs it just doesn't output anything at all, #app is blank... randomly.
In my test.log I see how the Vue app hits the JSON endpoint of my back-end and how it renders data with a 200.
For the life of me I can't imagine how initial_load_completed can be true and false at the same time.
What I've tried?
Rebooted the machine (heh). Then reinstalled all software to latest versions.
Then spent about 2 days trying to get chrome to work on a "virtual" display to which I would connect to see what's going on... after some 218 iterations fixing various deps/errors and configurations and code and signs and more errors and so on I just gave up.
Driver definition:
Webdrivers.logger.level = :DEBUG
default_chrome_args = [ '--disable-extensions', '--no-sandbox', '--disable-dev-shm-usage', '--remote-debugging-port=9222', '--remote-debugging-address=0.0.0.0' ]
Capybara.register_driver :headless_chrome do |app|
capabilities = Selenium::WebDriver::Remote::Capabilities.chrome( loggingPrefs: { browser: 'ALL' }, chromeOptions: {
'args' => default_chrome_args + ['--headless', '--disable-gpu', '--window-size=1920,1600' ]
})
Capybara::Selenium::Driver.new app, browser: :chrome, desired_capabilities: capabilities
end
CSP's are disabled, tried with and without them anyway.
Yesterday I tried logging JS errors:
config.after(:each, type: [ :feature, :system ], js: true) do
errors = page.driver.browser.manage.logs.get(:browser)
if errors.present?
aggregate_failures 'javascript errrors' do
errors.each do |error|
expect(error.level).not_to eq('SEVERE'), error.message
next unless error.level == 'WARNING'
STDERR.puts 'WARN: javascript warning'
STDERR.puts error.message
end
end
end
end
... no luck.
config.after(:each, type: [ :feature, :system ], js: true) do
errors = page.driver.browser.manage.logs.get(:browser)
errors.each do |error|
STDERR.puts error.message
end
end
... also nada just like several other few variations of this code.
Can't even seem to get the examples to "puts :whatever" to stdout but that's another story.
Can someone kind at heart pretty please help a poor dumb me not lose all hair?
Something that is not clear from the code samples in your question, is whether you are actually applying the driver you are defining.
System tests will use the default driver, so you must set it explicitly:
RSpec.configure do |config|
config.before(:each, type: :system) {
driven_by :headless_chrome
}
end
It can also be applied on a per-scenario basis on feature tests:
RSpec.feature 'Balance' do
scenario 'check the balance', driver: :headless_chrome do
...
end
end

Rspec feature test: Cannot visit a path

I have rspec features tests that are all failing because i cannot visit the indicated path. They all seems to be stuck at the root path after logging in. A screenshot shows that the page still remains on the root path. The test steps work on the browser, which means that the routing is correct. Any ideas?
I am getting the below error message for the test:
Failure/Error: page.evaluate_script('jQuery.active').zero?
Extract of my feature spec test:
describe 'follow users' do
let!(:user) { FactoryGirl.create(:user) }
let!(:other_user) { FactoryGirl.create(:friend) }
describe "Managing received friend request", js: true do
let!(:request) { Friendship.create(user_id: other_user.id, friend_id: user.id, accepted: false) }
before do
login_as(user, :scope => :user)
visit followers_path
end
it 'friend request disappear once user clicks accept' do
click_on "Accept"
wait_for_ajax
expect(current_path).to eq(followers_path)
expect(page).to have_css(".pending-requests", text: "You have 0 pending friend requests")
expect(page).to_not have_css(".pending-requests", text: other_user.name)
expect(page).to_not have_link("Accept")
expect(page).to_not have_link("Decline")
end
end
end
The issue here is you're calling 'wait_for_ajax' either on a page that doesn't include jQuery or at a time when it hasn't yet been loaded. The solution is to stop using wait_for_ajax and instead use the Capybara expectations/matchers as designed. There are very very few cases where wait_for_ajax is actually needed and even then it's usually a sign of bad UI decisions (no indication to the user something is happening). You should also not be using the eq matcher with current_path and should be using the Capybara provided have_current_path matcher instead since it has waiting/retrying behavior like all of the Capybara provided matchers.
it 'friend request disappear once user clicks accept' do
click_on "Accept"
expect(page).to have_current_path(followers_path)
expect(page).to have_css(".pending-requests", text: "You have 0 pending friend requests")
expect(page).to_not have_css(".pending-requests", text: other_user.name)
expect(page).to_not have_link("Accept")
expect(page).to_not have_link("Decline")
end
If that doesn't work for you, then either the button click isn't actually triggering page changes (check your test log), your Capybara.default_max_wait_time isn't set high enough for the hardware you're testing on, your login_as statement isn't actually logging in the user (although then I would expect the click on the accept button to fail), or you have a bug in your app.
If it's that login_as isn't actually logging in then make sure the server being used to run the AUT is running in the same process as the tests, if you're using puma that means making sure in the output it doesn't say it' s running in clustered mode.
Try to this approach to wait for all the ajax requests to finish:
def wait_for_ajax
Timeout.timeout(Capybara.default_wait_time) do
active = page.evaluate_script('jQuery.active')
until active == 0
active = page.evaluate_script('jQuery.active')
end
end
end
Taken from: Wait for ajax with capybara 2.0

Teardown called in the middle of a test Capybara

I have been trying to create the following test :
Edit a model (client side), check if the view is updated and if the model changed in database.
there is the code :
test 'a' do
user = User.joins(:organization_users).find_by organization_users: { role: OrganizationUser.roles.values_at(:ORGANIZER, :ADMINISTRATOR) }
sign_in_user user
criterion = create(:criterion, scoring_id: #scoring.id, name: "Test criterion name",
description: "Test description")
step = create(:step, criterion_id: criterion.id)
visit "scorings/" + (#scoring.id).to_s + "/criteria"
find("#criteria > div > div > a > i").click()
fill_in 'name', with: 'New name'
fill_in 'description', with: 'New description'
find('#criterion-modal > div:nth-child(2) > form > div:nth-child(4) > input').click()
criterion = criterion.reload
assert criterion.name == 'New name'
end
`
Driver :
Capybara.register_driver :poltergeist do |app|
Capybara::Poltergeist::Driver.new app , { phantomjs: Phantomjs.path }
end
Capybara.javascript_driver = :poltergeist
Capybara.current_driver = Capybara.javascript_driver
Teardown :
teardown do
DatabaseCleaner.clean
ActiveRecord::Base.connection.close
Capybara.reset_sessions!
end
As you can see at the end of the test i reload the criterion, but when i do that the teardown function is called. After that the Database is cleaned and i get the error "cant find criterion id:1". I'm only using minitest , factory girl and Capybara. So what i want to understand is why Teardown is called since its not the end of the test and how can i fix that ?
Thank you.
You don't show what you have setup for your teardown method, nor do you specify what driver you are using with Capybara. However, since the test code and the teardown are run in the same thread there really is no way for the teardown to run before the test has ended. What is possible (when using a JS capable driver, where clicks are processed asynchronously) is for the teardown to run before a click is processed/handled by the app code. That would mean the "cant find criterion id:1" would actually be coming from your controller code. The reason for this is that you're not actually checking for anything on the page to change after clicking so the test just keeps on moving, finishes (failing the assertion), the teardown cleans and the controller action can't find the record. Something like
assert_text 'Criterion updated' # if a message is displayed on successful update
or
assert_current_path("scorings/#{#scoring.id}") # whatever path it redirects to after updating
after the click and before your reload
On a side note - Using long selectors like '#criterion-modal > div:nth-child(2) > form > div:nth-child(4) > input' will lead to really brittle tests -- It would be much nicer to use simpler selectors or the capybara click_button type helpers if possible

Rspec with Capybara sometimes not pass tests

I have problem with testing Rails Application. My tests generally work perfectly. But sometimes tests will fail when I type some features test for modal bootstrap window, or notify with success/error [js]. How can I resolve this problem ?
I'm using Rspec, Capybara, Rails4.2, PhantomJs, Poltergeist as JS driver. Tests is running locally and in Wercker. In test mode, every bootstrap animation is disabled. What perhaps I do wrong ?
Test:
scenario 'return deutsch default title' do
find('.f-edit-item', match: :first).click
find('a', :text => 'Lang').click
find('a', :text => t('menu.languages.de')).click
find('.f-reset-button', match: :first).click
expect(page).to have_field('menu_item[title]', with: 'Exhibitions_de')
end
Output:
Objects Restore Language restore title translations exist for deutsch translation return deutsch default title
Failure/Error: expect(page).to have_field('object_item[title]', with: 'Exhibitions_de')
expected to find field "object_item[title]" with value "Exhibitions_de" but there were no matches. Also found "", "", which matched the selector but not all filters.
When I click manually, everything is working. When I run this test, sometimes passed, sometimes not. Form is in bootstrap modal. Curiosity: When I add save_and_open_page before find('.f-reset-button', match: :first).click test is passed always(5x in a row)
Because the tests are to do with a Bootstrap modal, my guess is that the test is searching the page for the matching elements, BEFORE the modal has loaded in the DOM.
Edit: As #TomWalpole pointed out, it should be enough to override Capybara's max wait time like so:
expect(page).to have_field('menu_item[title]', with: 'Exhibitions_de', wait: 1.0)
But if you are loading the contents of your modal via AJAX, you may need to force a wait for AJAX to complete the expect line. Here is a good guide on how to do this.
Specifically you need:
# spec/support/wait_for_ajax.rb
module WaitForAjax
def wait_for_ajax
Timeout.timeout(Capybara.default_wait_time) do
loop until finished_all_ajax_requests?
end
end
def finished_all_ajax_requests?
page.evaluate_script('jQuery.active').zero?
end
end
RSpec.configure do |config|
config.include WaitForAjax, type: :feature
end
And then your test would become:
scenario 'return deutsch default title' do
find('.f-edit-item', match: :first).click
find('a', :text => 'Lang').click
find('a', :text => t('menu.languages.de')).click
find('.f-reset-button', match: :first).click
wait_for_ajax
expect(page).to have_field('menu_item[title]', with: 'Exhibitions_de')
end

capybara waiting for ajax without using sleep

I'm using Capybara 2.x for some integration tests for a large Rails/AngularJS app and I've come across a test in which I need to put a sleep to get it working.
My test:
describe "#delete", js: true do
it "deletes a costing" do
costing = Costing.make!
visit "/api#/costings"
page.should have_content("General")
click_link "Delete" # Automatically skips the confirm box when in capybara
sleep 0.4
page.should_not have_content("General")
end
end
The code it tests is using ng-table which takes a split second to update, without that sleep it will fail. Capybara used to have a wait_until method for this but it's been taken out. I found this website: http://www.elabs.se/blog/53-why-wait_until-was-removed-from-capybara but cannot get any of the recommended alternatives working for this problem.
Here is the code I'm testing.
# --------------------------------------------------------------------------------
# Delete
# --------------------------------------------------------------------------------
$scope.destroy = (id) ->
Costing.delete (id: id), (response) -> # Success
$scope.tableParams.reload()
flash("notice", "Costing deleted", 2000)
This updates the ng-table (tableParams variable) which is this code
$scope.tableParams = new ngTableParams({
page: 1,
count: 10,
sorting: {name: 'asc'}
},{
total: 0,
getData: ($defer, params) ->
Costing.query {}, (data) ->
# Once successfully returned from the server with my data process it.
params.total(data.length)
# Filter
filteredData = (if params.filter then $filter('filter')(data, params.filter()) else data)
# Sort
orderedData = (if params.sorting then $filter('orderBy')(filteredData, params.orderBy()) else data)
# Paginate
$defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()))
})
Try bumping the Capybara.default_wait_time up to 3 seconds or 4.
If that fails, try changing the spec to look for the flash notice message before it checks to see if the item has been removed from the page. (Assuming the flash message gets rendered in the HTML body)
describe "#delete", js: true do
it "deletes a costing" do
costing = Costing.make!
visit "/api#/costings"
page.should have_content("General")
click_link "Delete"
page.should have_content("Costing deleted")
page.should_not have_content("General")
end
end
Edit - removed explanation because it was incorrect.

Resources