Why your Cucumber feature loses cookies when run under Selenium
When your Cucumber feature seems to forget cookies / sessions when you run it with Selenium check if the test travels in time like here:
Given the date is 2017-10-20
When I sign in
Then I should see "Welcome!"
What happens here is that the Rails application serving pages runs in 2017, but the process running your browser still lives today. This huge gap in time will expire most cookies immediately.
If all you need is to freeze the time to a date, a workaround is to travel to the future instead.
Updated: Capybara: Check that a page element is hidden via CSS
- The step we used in the past (
Then "foo" should not be visibile
) doesn't reliably work in Selenium features. - I overhauled the entire step so it uses Javascript to detect visibility in Selenium.
- The step has support for jQuery and Prototype projects, so it should be a drop-in replacement for all your projects.
- For Rack::Test the step no longer uses XPath so you should be able to understand it when you are not a cyborg :)
- There were some other cards detailing alternative steps to detect visibility. I deleted all these other cards s...
Use the back button in Cucumber
In order to go back one page in your Cucumber tests, you can use the following step definition for Capybara:
When(/^I go back$/) do
visit page.driver.request.env['HTTP_REFERER']
end
If you're on Webrat, this should work:
When(/^I go back$/) do
visit request.env["HTTP_REFERER"])
end
An improved version of this step is now part of our gem spreewald on Github.
Embed Google Analytics code for some environments only
When you use google analytics to track your visitors interactions, you should ensure that it runs on your production site only. Otherwise it will spoil your statistics. To prevent this, test for the right environment and place the JS-code afterwards:
- if Rails.env.production?
:javascript
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXXX-X']);
_gaq.push(['_trackPageview']);
...
Parallel Rspec with RTeX
Running projects parallel makes some trouble with PDF generation. Use geordi rspec spec
to force sequential tests for the whole application or failed specs only.
geordi rspec
RTeX::Document::GenerationError in '...'
Could not find result PDF document.pdf after generation.
Check .../document.log
The document will show you, that RTeX tries to generate a PDF document out of a HTML file, which won't work.
The Plight of Pinocchio: JavaScript's quest to become a real language - opensoul.org
Great presentation about writing Javascript like you write everything else: Well-structured and tested.
JavaScript is no longer a toy language. Many of our applications can’t function without it. If we are going to use JavaScript to do real things, we need to treat it like a real language, adopting the same practices we use with real languages.
This framework agnostic talk takes a serious look at how we develop JavaScript applications. Despite its prototypical nature, good object-oriented programming principles are still relevant. The...
Raise when there's a I18n translation missing
The translation method translate
and its alias t
have bang brothers: translate!
and t!
. They will raise I18n::MissingTranslationData
on a missing translation instead of printing a string like translation missing: de.custom.failure
.
To turn on raising globally, you need to replace the default exception handler. The attached initializer makes I18n just raise any exception (in a development or test environment).
ActiveRecord meets database views with scenic
Using Scenic, you can bring the power of SQL views to your Rails application without having to switch your schema format to SQL. Scenic provides a convention for versioning views that keeps your migration history consistent and reversible and avoids having to duplicate SQL strings across migrations. As an added bonus, you define the structure of your view in a SQL file, meaning you get full SQL syntax highlighting in the editor of your choice and can easily test your SQL in the database console during development.
[https://robots.thoughtb...
Configuring User Agents with Capybara + Selenium Webdriver
A while ago we were working on an application that had an entire version specially created for mobiles, such as the iPhone. This specific application was entirely tested with Capybara, Steak and Selenium Webdriver. Although the test suite wasn’t the fastest one in the world, the web application was very well tested, and to guarantee that we would also be testing the mobile version, we would have to simulate an iPhone user agent accessing the application.
But wait, you might be thinking that we are not able to change browser headers while ...
Cucumber: Wait for any requests to finish before moving on to the next scenario
Background
Generally, Selenium tests use the browser to interact with the page. If it's unavailable, a timeout error is thrown.
Now, consider a scenario like this:
@javascript
Scenario: Receive an e-mail after clicking the fancy link
When I follow "fancy link"
Then I should have an e-mail with the subject "Hello"
When the last step in the scenario passes, you are done. Right? Wrong.
Why it's not enough
What if clicking our "fancy link" above sends the e-mail that we expect, but it also does stuff on the server...
Force SSH client to use password authentication instead of public key
To test if you can connect to a host using password authentication and explicitly deny public key authentication:
ssh -o PreferredAuthentications=password -o PubkeyAuthentication=no user@host
This also works for Secure Copy:
scp -o PreferredAuthentications=password -o PubkeyAuthentication=no local.file user@host:/path/to/remote.file
Geordi hints
Reminder of what you can do with Geordi.
Note: If you alias Geordi to something short like g
, running commands gets much faster!
Note: You only need to type the first letters of a command to run it, e.g. geordi dep
will run the deploy
command.
geordi deploy
Guided deployment, including push, merge, switch branches. Does nothing without confirmation.
geordi capistrano
Run something for all Capistrano environments, e.g. geordi cap deploy
geordi setup -t -d staging
When you just clon...
VNC browser disappears while typing
We often use the Then console
step from spreewald in combination with geordi vnc
from geordi to debug tests within a real browser. Sometimes when you type in the browser it suddenly disappears. You will only see a grey screen then.
This will always happen if you press the d
key. Press the d
key again and the browser will appear again.
ActionView::Template::Error (dump format error for symbol(0x6d))
I recently encountered the error above when I was running selenium tests.
Thanks to a post on stackoverflow I found out that clearing all files in tmp/cache in my project folder made the issue go away.
Testing state_machine callbacks without touching the database
You should test the callback methods and its correct invocation in two separate tests. Understand the ActiveRecord note before you move on with this note.
Say this is your Spaceship
class with a transition launch
and a release_docking_clamps
callback:
class Spaceship
state_machine :state, :initial => :docked do
event :launch do
transition :docked => :en_route
end
before_transition :on => :launch, :do => :release_doc...
How to silence UTF-8 warnings on Rails 2.3 with Ruby 1.9
Rails 2.3.16+ on Ruby 1.9 causes warnings like this:
.../gems/activesupport-2.3.17/lib/active_support/core_ext/string/output_safety.rb:22: warning: regexp match /.../n against to UTF-8 string
Many thanks to grosser for supplying a monkey-patch for Rails 2.3 (Commit f93e3f0ec3 fixed it for Rails 3). Just put it into config/initializers/
to make those warnings go away.
Since we're using RSpec on mos...
How to set the default monospace font on Xfce (Xubuntu)
While you can set your own font in your terminal or other tools, it will not change the default "Monospace" font that some applications use.
To change that, edit ~/.fonts.conf
and add settings for the "monospace" family. Here is how it looks on my machine now:
<fontconfig>
<match target="pattern">
<test qual="any" name="family">
<string>monospace</string>
</test>
<edit name="family" mode="assign">
<string>DejaVu Sans Mono</string>
</edit>
</match>
</fontconfig>
...
Check whether a Paperclip attachment exists
Don't simply test for the presence of the magic Paperclip attribute, it will return a paperclip Attachment
object and thus always be true:
- if user.photo.present? # always true
= image_tag(user.photo.url)
Use #exists?
instead:
- if user.photo.exists?
= image_tag(user.photo.url)
Use byebug on Ruby 2+
The debugger
gem does not seem to be properly working on Ruby 2. Use byebug
instead!
Byebug is a simple to use, feature rich debugger for Ruby 2. It uses the new TracePoint API for execution control and the new Debug Inspector API for call stack navigation, so it doesn't depend on internal core sources. It's developed as a C extension, so it's fast. And it has a full test suite so it's reliable. Note that byebug works only for ruby 2.0.0 or newer. For...
How to fix: Bundler 1.13 breaks parallel_tests
When running tests via parallel_tests, you may encounter an error:
cannot load such file -- parallel_tests/gherkin/runtime_logger
Error creating formatter: ParallelTests::Gherkin::RuntimeLogger (LoadError)
This will happen when you upgrade Bundler to version 1.13.x and appears to be "by design" since there is a Bundler config option to restore previous behavior.
You can fix it by setting that flag. You should commit the resulting config file into the repository!
bundle config --local disable_exec_load true
There is a Git...
RCov: The difference between "code coverage" and "total coverage"
Code coverage is the ratio of code lines kissed by a test vs. the total number of lines in your source files. This sounds meaningful, but isn't.
Total coverage additionally ignores whitespace and comments when computing the coverage ratio, which is what you want.
Beware: Nested Spreewald patiently blocks are not patient
Note: The behaviour of Spreewald's within
step is as described below for version < 1.9.0; For Spreewald >= 1.9.0 it is as described in Solution 1.
When doing integration testing with cucumber and selenium you will often encounter problems with timing - For example if your test runs faster than your application, html elements may not yet be visible when the test looks for them. That's why Spreewald (a collection of cucumber steps) has a concept of doing things patiently
, which means a given b...
Bash script to list commits by Pivotal Tracker ID
The main benefit of our convention to prefix commits by their corresponding Pivotal Tracker ID is that we can easily detect commits that belong to the same story. You can either do that manually or use the bash script below by copying it somewhere to your .bashrc
.
# Usage: ptcommits 123456
function ptcommits {
if test "$1"
then
local PTID=$(echo "$1" | grep "[0-9]*" -o) # Allow URLs
git log --onel...
Change how Capybara sees or ignores hidden elements
Short version
- Capybara has a global option (
Capybara.ignore_hidden_elements
) that determines whether Capybara sees or ignores hidden elements. - Prefer not to change this global option, and use the
:visible
option when callingpage.find(...)
. This way the behavior is only changed for this onefind
and your step doesn't have confusing side effects. - Every Capybara driver has its own notion of "visibility".
Long version
Capybara has an option (Capybara.ignore_hidden_elements
) to configure the default...