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


How do I use phantomjs uploadFile with Capybara and poltergeist?

Question:

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 (http://phantomjs.org/api/webpage/method/upload-file.html) 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]); "
  end

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

  # Trigger the fake drop event
  page.execute_script(js_script)
end

which comes from https://github.com/teampoltergeist/poltergeist/issues/342 and works in selenium. The user that posted that says he has it working in poltergeist though.


Answer:

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


Related:


Unable to click in CasperJS


javascript,web-crawler,phantomjs,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('http://sts.kma.go.kr/jsp/home/contents/climateData/smart/smartStatisticsSearch.do', function() { this.echo('START'); }); casper.then(function() { this.capture("1.png"); this.mouse.click('li[class="item1"]'); casper.wait(5000, function() { this.capture("2.png"); }); });...

Timeout for webdriver.PhantomJS in python?


python,selenium,selenium-webdriver,phantomjs
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 = "http://aminer.org/search/jie%20tang" browser.get(url) ...

I dont know how to add Proxy to my Phantomjs script


python,proxy,phantomjs,casperjs
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...

What is the difference between User.make and User.new?


ruby-on-rails,unit-testing,rspec,capybara
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...

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


ruby,selenium,cucumber,capybara
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...

Phantomjs javascript inheritance misunderstanding


javascript,inheritance,phantomjs
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...

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


javascript,phantomjs,screenshot
When I follow this tutorial (http://phantomjs.org/screen-capture.html) 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(); page.open('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...

Success compilation of phantomjs on Raspberry 2 but not executing (libjpeg.so.8)


compilation,phantomjs,raspbian,libjpeg,raspberry-pi2
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...

Click a button to download a file using CasperJS


javascript,unit-testing,phantomjs,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...

Logging for rspec selenium/capybara tests running in Browserstack


ruby,selenium,rspec,capybara,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,...

Faking instance variable in RSpec and Capybara feature spec


ruby-on-rails,ruby,rspec,capybara
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...

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


ruby-on-rails,angularjs,rspec,capybara
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);...

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


javascript,json,get,phantomjs,casperjs
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: https://api.twitter.com/1.1/search/tweets.json?q=casperjs Here is my code : var casper = require('casper').create({ verbose: true, logLevel: 'debug', pageSettings: { loadImages: false,...

Can't install phantojm on server


phantomjs
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...

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


backbone.js,coffeescript,phantomjs,mocha,chai
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 =...

PhantomJS javascript wait until function complete


javascript,asynchronous,phantomjs,wait
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(); page.open (address, function(){ //parse json, set amount to something (usually...

Run block once before all capybara tests


ruby-on-rails,ruby,rspec,capybara
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...

How to handle browser prompts in CasperJS


javascript,phantomjs,casperjs,prompt
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 ()...

Rasterization with Javascript looks different on Apache server


javascript,apache,phantomjs,server,rasterizing
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,...

Switch between windows with frames


ruby,capybara
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...

How to use DOMParser in PhantomJS?


javascript,dom,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? ...

PHP in Javascript for PhantomJS + Highcharts


javascript,php,highcharts,phantomjs
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:...

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


php,ubuntu,laravel,phantomjs
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...

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


ruby-on-rails,ruby,rspec,capybara
I am trying to test a controller create method in a rails app using RSpec as shown below: def create @user = User.new(user_params) if @user.save redirect_to user_path(@user.id) 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...

Nightmare, PhantomJS and extracting page data


node.js,phantomjs,nightmare
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...

Using phantomjs print proxy it used to access website


python,proxy,phantomjs
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...

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


javascript,phantomjs,casperjs
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: "+resourceError.id, "ERROR" Since evaluate() executes the code in the context of the...

Capybara::ElementNotFound radio by id


ruby-on-rails-4,capybara
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 Process doesn't exit


java,selenium,phantomjs
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...

phantomjs --web-security=no


security,phantomjs,casperjs
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?...

node-horseman async not working?


node.js,asynchronous,phantomjs
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...

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


javascript,jquery,ajax,phantomjs,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...

Capybara - Determine if selector count has changed


ruby,rspec,capybara
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...

Fill in Editor textarea using capybara-webkit


editor,capybara,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' %> <%...

Unsafe JavaScript attempt to access in capserjs [duplicate]


phantomjs,casperjs
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....

Not possible to trigger GWT listbox ChangeHandler using CasperJS


javascript,gwt,phantomjs,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 set text into Summernote textarea with Capybara + Poltergeist


rspec,capybara,poltergeist,summernote
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...

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


java,selenium-webdriver,phantomjs,load-testing
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...

CasperJS/SpookyJS css selector is existing and not-existing


javascript,css-selectors,web-scraping,phantomjs,spookyjs
I have a strange problem during screen scraping with spookyjs / capserjs. I want to catch information from the following website: 'https://www.rwe-smarthome.de/is-bin/INTERSHOP.enfinity/WFS/RWEEffizienz-SmartHome-Site/de_DE/-/EUR/ViewApplication-DisplayWelcomePage'. Because the site contains more than one page of products I want to open the other sites too. Normally one could use this.click(selector, function() {}); to achieve this....

Phantomjs disable javascript in page but enable included javascript


javascript,phantomjs
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; page.open('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;...

Pass complete code to phantomjs


go,phantomjs,exec
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...

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


javascript,jquery,javascript-events,phantomjs,html-input
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....

How to map browser dialog using capybara/selenium


ruby,selenium,capybara
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...

Is element visible?


ruby,capybara
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,...

pass HTML to phantom and render it to PDF


node.js,pdf,phantomjs
Normally in phantom you would be able to do something like this: phantom = require('phantom') phantom.create(function(ph){ ph.createPage(function(page) { page.open("http://www.google.com", 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


ruby-on-rails,selenium,rspec,websocket,capybara
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...

phantomjs image width not getting as expected


javascript,phantomjs,screenshot,viewport,browser-width
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 }; page.open("http://www.google.com", function start(status) { page.render('google_home.png'); phantom.exit(); but,...

PhantomJS pass argument to evaluate


javascript,node.js,phantomjs,nightmare
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...

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


javascript,node.js,phantomjs,headless-browser
I have the following in my code: phantom.createPage(function(page){ page.onCallback = function(data) { console.log("ph callback: ", data); }; page.open(req.query.testUrl, 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(window.mocha.constructor.name); }, function(){ console.log('finished'); page.close();...

Scrolling with phantomJs Selenium


java,selenium,selenium-webdriver,phantomjs
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...