ProTip: Automagically setup PhantomJS for Capybara+Poltergeist
Published on Jul 27, 2016 • Ruslan Ledesma-Garza
Are you looking for a way to install PhantomJS automatically on program start?
This ProTip is for you.
Consider the following program titles.rb.
The example prints the titles of posts that appear in the main page of this blog.
The example works fine when command phantomjs is in $PATH.
Otherwise you get this ugly error.
In this case, try the following program magic-titles.rb.
Line MAGIC installs PhantomJS in ~/phantomjs, so you might want to remove that directory afterwards.
Now you get titles.
The elided part consists of a list files that are installed in ~/.phantomjs.
How does MAGIC work?
Line MAGIC installs PhantomJS and tells Poltergeist where to find command phantomjs.
Installation happens when MAGIC calls method
Phantomjs.path.
The code that does the installation is located in method
Phantomjs::Platform#install!.
The code installs PhantomJS in ~/.phantomjs when PhantomJS is not
installed there and is not in your $PATH.
Do apply this ProTip when you are doing a one-off task.
Do remember to remove directory ~/phantomjs when you don’t need it anymore.
Do not apply this ProTip when installing PhantomJS by other means
gives a shorter development cycle. For example, when you run you
tests in a Docker container, install PhantomJS and either do not discard the
container’s
data or
create a new image from the last state of the
container.
This way you will not lose time installing PhantomJS every time you
run tests.