capybara,phantomjs,poltergeist , How do I use phantomjs uploadFile with Capybara and poltergeist?

How do I use phantomjs uploadFile with Capybara and poltergeist?


Tag: capybara,phantomjs,poltergeist

I am trying to attach a file in my spec, but the capybara attach_file method does not work for me in poltergeist (it returns true but nothing gets attached). It does work in Selenium, but for other reasons I want to use poltergeist. I know that the phantomjs uploadFile method ( simulates a user interacting with the file dialog which is what I think I need to do. I cannot figure out how to use it though in my Capybara spec.

I am trying to use

def drop_files(files, css_selector)
  js_script = 'fileList = Array(); '
  files.count.times do |index|
    # Generate a fake input selector
    page.execute_script("if ($('#seleniumUpload#{index}').length == 0) { " \
                        "seleniumUpload#{index} = window.$('<input/>')" \
                        ".attr({id: 'seleniumUpload#{index}', type:'file'})" \
                        ".appendTo('body'); }")

    # Attach file to the fake input selector through Capybara
    attach_file("seleniumUpload#{index}", files[index], visible: false)
    # Build up the fake js event
    js_script << "fileList.push(seleniumUpload#{index}.get(0).files[0]); "

  js_script << "e = $.Event('drop'); "
  js_script << "e.dataTransfer = { files : fileList }; "
  js_script << "$('#{css_selector}').trigger(e);"

  # Trigger the fake drop event

which comes from and works in selenium. The user that posted that says he has it working in poltergeist though.


It turns out file uploading is currently broken on Phantomjs 2.0. I downgraded v1.9.8 and attach_file works now.


PhantomJS pass argument to evaluate

I have a small test app using mightmarejs as a wrapper for phantomjs I want to test for the existence of a class on an element. I have this code: new Nightmare() .goto(baseURL) .evaluate(function() { return document.querySelector('body'); }, function(element) { element.className.should.equal(expected) callback(); }) .run(); How can I pass an argument...

If I stub out .save method in my controller test how can I check the correct show template is rendered?

I am trying to test a controller create method in a rails app using RSpec as shown below: def create @user = if redirect_to user_path( else render new_user_path flash[:error] = "User not saved" end end However if i stub out .new to prevent the test from using Active...

Using $.ajaxStop() to determine when page is finished loading in CasperJS

So far in my tests written in CasperJS, I've been using waitForSelector() on page-specific elements to determine if a page has fully loaded (including all the async ajax requests). I was hoping to come up with a more standard way of waiting for page load and was wondering if the...

PHP in Javascript for PhantomJS + Highcharts

I have just configured phantomjs which is working fine. I have it installed in order to create charts from highcharts and include them in automated email through cronjobs, based on user's info. This will be done in php and right now I have the execution running perfectly. My php is:...

Run block once before all capybara tests

I'm using Capybara with Rspec for integration testing a rails app. Is there any way to run a before block once before the first Capybara test runs without it running before every feature spec? Putting a block in my RSpec.configure block as such causes it to run before each feature...

Faking instance variable in RSpec and Capybara feature spec

I'm trying to set up some feature specs before I get into refactoring some of my company's old code. It's kind of an unconventional setup, but I was able to figure out enough about test doubles to bypass the authentication enough to get started. One problem I'm still having is...

Pass complete code to phantomjs

I'm writing a service in Go and I'm using phantomJS to generate an image from a given url. From my Go program, I'm using Exec to start the phantomJS binary. This works fine, but now I'm looking for a way to pass the complete code, together with the call which...

Anyone successfully used jonnyw's “php phantomjs” with laravel, in a ubuntu envirement?

Anyone sucessfully used jonnyw's "php phantomjs" with laravel, in a ubuntu envirement? I do not know if I am doing anything wrong, but I am questioning if it would be possible that it is not possible to use it with laravel in linux... I get all the time "Error when...

PhantomJS Process doesn't exit

I am creating several instances of PhantomJSDriver and can make requests to websites and get the data I want. Each instance is spawned via the following: WebDriver driver = BrowserUtils.getInstance().getBrowser(); When I'm done I attempt to do the following: driver.close(); driver.quit(); driver = null; However, if I open up a...

Switch between windows with frames

I have main window with frames and a popup where I do some operations: within_frame("MainFrame") do find("btnNewItem").click #opens popup window end within_window(windows.last) do within_frame("frmFrame2"){ some_operations find("btnOK").click #closes a popup } end within_window(switch_to_window(windows.first)) do within_frame("MainFrame") do find("btnDeleteItem").click #deletes item accept_popup_dialog end end But when operations are done in popup window and...

What is the difference between User.make and

In Capybara docs, it has describe "the signin process", :type => :feature do before :each do User.make(:email => '[email protected]', :password => 'password') end it "signs me in" do visit '/sessions/new' within("#session") do fill_in 'Email', :with => '[email protected]' fill_in 'Password', :with => 'password' end click_button 'Sign in' expect(page).to have_content 'Success' end...

Using phantomjs print proxy it used to access website

can someone point me in the right direction. Just need some documentation. I manually input a proxy, but I think it might be by passing it. I want to test my script to see if its actually going through my proxy with phantom. It looks like I successfully went through...

Is element visible?

I have an error when I try to check if some element is visible. My method is the following: if find(:xpath, "//td[text()='#{subtab}']").visible? find(:xpath, "//td[text()='#{subtab}']").click else find(:xpath, "//td[text()='#{tab}']").click find(:xpath, "//td[text()='#{subtab}']").click end In if find(:xpath, "//td[text()='#{subtab}']").visible?, I have: Capybara::ElementNotFound: Unable to find xpath "//td[text()='Plan List2']" but when the element is correctly visible,...

Nightmare, PhantomJS and extracting page data

I'm new to Nightmare/PhantomJS and am struggling to get a simple inventory of all the tags on a given page. I'm running on Ubuntu 14.04 after building PhantomJS from source and installing NodeJS, Nightmare and so forth manually, and other functions seem to be working as I expect. Here's the...

Fill in Editor textarea using capybara-webkit

I'm using a markdown editor on my page, which I'm trying to target, and fill in, using capybara-webkit, but without any luck. My template looks like this <%= simple_form_for form, url: url, method: :put do |f| %> <%= f.input :notes, as: :text %> <%= f.button :submit, class: 'fluid' %> <%...

How to use phantomjs to take screen shot with dynamic data visualization

When I follow this tutorial ( to do a screen capturing, I got some problem about dynamic data visualization. In that tutorial, it uses some code like: var page = require('webpage').create();'http://localhost:8080/index.html', function() { page.render('screenshot.png'); phantom.exit(); }); But this seems work only with static page. I wonder if I have...

PhantomJS load same page multiple times does not work, cannot clear cache

I am trying to use PhantomJS for load testing website, but I am facing this problem, PhantomJS just loads website once, after that it does not actually hit it, I see that there are many discussion for people asking this feature for load testing purpose but looks like its not...

Capybara - Determine if selector count has changed

I am writing a test to confirm that hidden (Note: not destroyed. They are hidden using a boolean DB field) items no longer show up on my page. I know with Capybara I can use the following to confirm a selector's count: expect(page).to have_selector('input', count: 12) Is it possible to...

Logging for rspec selenium/capybara tests running in Browserstack

I am building a set of automated regression tests in ruby using rspec and capybara. To give you an idea of a test, imagine logging in to a website, adding a new data item with all of its fields, saving it, validating the new row, updating the row, changing fields,...

Phantomjs javascript inheritance misunderstanding

I have following files: run.js (to run whole script) animal.js (parent abstract class for cat) animal/cat.js (child class for animal, on which I want to invoke methods) run.js var cat = require('./animal/cat').create('Tom'); console.log( cat.petName ); console.log( cat.paws ); cat.voice(); animal.js function animal(){ this.paws = 4; } exports.create = function(){ return...

Can't load json from url with Casper Js -> “Loading resource failed with status=fail”

I am new to casper js and I would like to retrieve a json object from a get request. The message I get is the following : Loading resource failed with status=fail: Here is my code : var casper = require('casper').create({ verbose: true, logLevel: 'debug', pageSettings: { loadImages: false,...

After-hook scenario.exception does not exist in Cucumber 2.0

I'm using Capybara, Cucumber, and Selenium-Webdriver for basic web testing. If a test fails, I want to capture the failure message and send it to a separate log file. Cucumber offers hooks to catch the failure message after the scenario fails (from their wiki): After do |scenario| if scenario.failed? subject...

WebApp doesn't recognize that an input field was changed when set with jQuery in PhantomJS

I open telegram with PhantomJS and try to fill phone number input with evaluate page like below: page.evaluate(function(){ $("input[name='phone_number']").val("123456789"); }); When PhantomJS clicks on next button with jQuery the alert massage says "tel input is empty" but when the page is rendered we can see numbers in the input field....

node-horseman async not working?

I'm using node-horseman to ( hopefully ) allow me to carry out asynchronous phantomjs operations to achieve async headless browsing. The numbers in the array are at this stage irrelevant, I've just stripped the code down to the bare minimum to demonstrate the problem I'm having. When I run the...

Success compilation of phantomjs on Raspberry 2 but not executing (

In my raspberry 2 with updated version of OSMC I would like to use PhantomJS with selenium in python and tried to compile it. Following this link: How to compile phantomjs on the raspberry pi 2 And this link: Adding swap for the raspberry pi Created swap file of 16Gb...

Rasterization with Javascript looks different on Apache server

I am using phantomjs to rasterize an html page that I'm creating dynamically with javascript/php. It looks fine when testing on my localhost, but when testing on an apache server, it appears to blow the image up, causing it to be formatted wrong (extends to two pages instead of one,...

Timeout for webdriver.PhantomJS in python?

I just use selenium-python. When I use webdriver.Firefox(), I can get the result. When I use webdriver.PhantomJS(), the result can't be returned (the script is hanging). Can anyone help me? browser = webdriver.PhantomJS(executable_path='./lib/phantomjs/phantomjs') url = "" browser.get(url) ...

Can't install phantojm on server

I'm having a difficult time getting phantomjs installed on my server. I haven't found very good directions anywhere and the best I've found give me errors when I try to complete them. As of now I'm following these steps and getting these errors. Successfully used putty to login as root...

Can rspec be used to feature test an integrated rails-angular app?

I have a very basic, integrated rails-angular app. It just renders a link, which uses data from a get request to rails: 'use strict'; angular.module('angularRspec.controllers') .controller('FightersController', function($scope, $http){ console.log("FightersController is loaded..."); $scope.fighters = []; $http.get('./fighters.json'). success(function(data, status){ $scope.fighters = data; console.log(status); console.log(data); }). error(function(data, status, headers, config) { console.log(status); console.log(headers);...

How to map browser dialog using capybara/selenium

What is the best way to handle browser dialogs (with ok/cancel buttons) using capybara/selenium? The way I found easiest is by running the following: dialog = page.driver.browser.switch_to.alert dialog.accept Any thoughts for a better approach? Whoever downed this post please give a valid reason... it's not helpful to down vote with...

Phantomjs disable javascript in page but enable included javascript

I am using phantomjs to retrieve CSS information from a page without execute its javascript. For example here is the code snippet. page.settings.javascriptEnabled = false;'file:///home/sample.html', function(status) { if (status !== 'success') { console.log('Unable to access network'); } else { page.includeJs("file:///home/sample.js", function() { var class = page.evaluate(function() { return document.querySelector('body').className;...

Capybara::ElementNotFound radio by id

I understand the syntax for Capybara choosing a radio button is the following choose("Label Name") I am running into an issue with doing this for a label that has its default name changed to an #id. Here is my HTML <label for="school_application_I_20"> Do you require an I-20 Form?</label> <br> <label...

phantomjs image width not getting as expected

when i take screenshots using phanomjs using the following code works fine and I am getting width as 1920px and height is not a problem for me. var webPage = require('webpage'); var page = webPage.create(); page.viewportSize = { width: 1920, height: 1080 };"", function start(status) { page.render('google_home.png'); phantom.exit(); but,...

Not possible to trigger GWT listbox ChangeHandler using CasperJS

I'm writing tests using CasperJS for legacy GWT (2.3) code. I can change the selected value of a ListBox. document.querySelector('#id_of_select').selectedIndex = 1; But this does not trigger the onChange() method of a change handler on the ListBox. I have tried manually dispatching a change event on the select element (jquery...

How to use DOMParser in PhantomJS?

The following snippet works correctly and returns a Document node in Firefox, Chrome and Safari web consoles. However, it returns null in PhantomJS 1.9.8. (new DOMParser()).parseFromString("<div></div>", "text/html"); Any idea why this is returning null? ...

How to handle browser prompts in CasperJS

The scenario is, when I click a button browser would show an alert which accepts user input field with OK and cancel buttons. Now please tell me how to handle this type of alert. As we know CasperJS doesn't displays the alert windows. This is the casperJS code casper.then(function ()...

Having trouble getting page.injectJs() to work in PhantomJS

I have the following in my code: phantom.createPage(function(page){ page.onCallback = function(data) { console.log("ph callback: ", data); };, function(status){ if(status !== 'success'){ page.close(); res.status(500) .send('Page "' + testUrl + '" could not be loaded.') .end(); return; } var result = page.injectJs('lib/my-test-script.js'); console.log('injectJS: ', result); page.evaluate(function(){ window.callPhantom(; }, function(){ console.log('finished'); page.close();...

Catch errors caused by evaluate() in CasperJS / PhantomJS?

I'm wondering why the following code isn't picking up errors output in the console by javascript code executed using the evaluate() method. casper.on 'resource.error', -> @echo 'Resource error: ' + "Error code: "+resourceError.errorCode+" ErrorString: "+resourceError.errorString+" url: "+resourceError.url+" id: ", "ERROR" Since evaluate() executes the code in the context of the...

I dont know how to add Proxy to my Phantomjs script

I've been having issues accessing websites and just realized that since the websites are controlled by my company I need to add a step in my script that shows the webpage I have my companies proxy IP or Im on their server. I hope that makes sense. For example if...

Backbone.Deferred.Model: Why the unittest is not run?

Here is the code in question. define (require) -> Backbone = require 'backbone' require 'backbone-deferred' class Data extends Backbone.Deferred.Model urlRoot: 'data' parse: (resp) -> resp.record or resp isValid: -> @get 'valid' # Newly introduced dataUrl: -> @get('data_url')?.replace /abc/, '' And here is the unit test define (require) -> Data =...

Unsafe JavaScript attempt to access in capserjs [duplicate]

This question already has an answer here: Using PhantomJS to embed all images of a webpage produces warnings but works 1 answer On each test run of casperjs test, the output closes with the following: Unsafe JavaScript attempt to access frame with URL about:blank from frame with URL file:///usr/lib/node_modules/casperjs/bin/bootstrap.js....

How to set text into Summernote textarea with Capybara + Poltergeist

I have a textarea which is using Summernote and I set onChange event to it. I want to write test with RSpec + Capybara + Poltergeist to confirm the onChange event is working. As far as I checked, the textarea displayed in browser is actually div tag with 'note-editable' css...

Scrolling with phantomJs Selenium

I am trying to get this particular code running for scrolling a webpage which is a type of pagination. It works like a charm with the Firefox driver, but when i use phantomJS it doesn't work and goes into infinite loop public class Drivers { public WebDriver phJS() { File...

CasperJS/SpookyJS css selector is existing and not-existing

I have a strange problem during screen scraping with spookyjs / capserjs. I want to catch information from the following website: ''. Because the site contains more than one page of products I want to open the other sites too. Normally one could use, function() {}); to achieve this....

Unable to click in CasperJS

I want to crawl the HTML data. And, I tried headless browser in CasperJS. But, Can't able to click. - The following is tried code in CapserJS. var casper = require('casper').create(); var mouse = require('mouse').create(casper); casper.start('', function() { this.echo('START'); }); casper.then(function() { this.capture("1.png");'li[class="item1"]'); casper.wait(5000, function() { this.capture("2.png"); }); });...

pass HTML to phantom and render it to PDF

Normally in phantom you would be able to do something like this: phantom = require('phantom') phantom.create(function(ph){ ph.createPage(function(page) {"", function(status) { page.render('google.pdf', function(){ console.log('Page Rendered'); ph.exit(); }); }); }); }); However instead of loading a webpage i already have some html i want to pass and render as a PDF....

Wait for Websocket Rails event to finish in test environment

I am using the Websocket Rails gem in my Rails application to send an event that triggers a refresh of part of the page. All is working fine, but in my testing (I am using Rspec + Capybara + Selenium) I can't seem to find a way to wait for...

Click a button to download a file using CasperJS

I want to write unit tests to download a file by clicking a form button using casperJS. I tried using document.getElementsByTagName to get to the button and clicked it in JavaScript's way. But I got an error message: TypeError: 'undefined' is not a function (evaluating 'inputs[1].click()') The segment of the...

PhantomJS javascript wait until function complete

I have a problem with a PhantomJS script. The script gets a JSON encoded string from a web page and does other things with it. The script: var address = address; var amount = 0; function changeAmount() { var page=require('webpage').create(); (address, function(){ //parse json, set amount to something (usually...

phantomjs --web-security=no

In the documentation for phantomjs, there is an option to turn off web security and allow XHR (cross domain requests). Does this present a security risk to a user if you are filling forms with credentials such as usernames and passwords and then downloading screenshots with casper/phantom?...