Run your own code before specific RSpec examples

You probably know about the possibility to tag scenarios in Cucumber to run your own piece of code before the actual scenario is run which looks like that:

@foo
Scenario: Do something
...

and you place the following snippet into support/env.rb:

Before('@foo') do
  puts "This is run every time a @foo tagged scenario is hit"
end    

You can tag RSpec examples like this:

it 'does something', :foo => true do
  ...
end

What you need is the following within the RSpec.configure do |config| block wit...

In MySQL, a zero number equals any string

In MySQL comparing zero to a string 0 = "any string" is always true!

So when you want to compare a string with a value of an integer column, you have to cast your integer value into a string like follows:

SELECT * from posts WHERE CAST(posts.comments_count AS CHAR) = '200' 

Of course this is usually not what you want to use for selecting your data as this might cause some expensive database operations. No indexes can be used and a full table scan will always be triggered.

If possible, cast the compared value in your application to...

RestClient sends XML Accept header by default

REST Client is a nice, simple HTTP client library for Ruby.

When you do a simple GET request like that:

RestClient.get 'http://example.com/'

it will result in this request beeing sent to www.example.com:

GET / HTTP/1.1
Accept: */*; q=0.5, application/xml
Accept-Encoding: gzip, deflate
Host: www.example.com

The application/xml accept header might lead to unexpected results on your server. You can force REST Client to ask the server for default text/html that way:

RestC...

How to overwrite and reset constants within Cucumber features

In order to save the original value of a constant, set the new value and restore the old value after a scenario was completed, you can use the following helper. It takes care of saving the old constant value, setting the new one without throwing warnings and resets the value with an After hook.

This module also enables you to introduce new global constants.
Since these newly defined constants do not have any value to be reset to,
they simply are deleted (remove_const) once the respective Cucumber step finishes.

You can copy the file at...

Cucumber step to test that a tooltip text exists in the HTML

Tooltips that are delivered through HTML attributes are encoded. Decode entities before checking for their presence.

Capybara:

Then /^there should( not)? be a(n encoded)? tooltip "([^"]*)"$/ do |negate, encoded, tooltip|
  tooltip = HTMLEntities.new.encode(tooltip) if encoded
  Then "I should#{negate} see \"#{tooltip}\" in the HTML"
end

Note

This step uses the htmlentities gem described in another card.

Ma...

Look up a gem's version history

Sometimes it might be helpful to have a version history for a gem, e.g. when you want to see if there is a newer Rails 2 version of your currently used gem.

At first you should search your gem at RubyGems. Example: will_paginate version history.

The "Tags" tab at GitHub might be helpful as well.

Fixing Graticule's "distance" for edge cases

Ever seen this error when using Graticule?

Numerical argument out of domain - acos

Similarly to the to_sql problem for some edge cases, Graticule::Distance::Spherical.distance (and possibly those of Graticule's other distance computation classes) is subject to Float rounding errors.

This can cause the above error, when the arc cosine of something slightly more than 1.0 is to be computed, e.g. for the (zero) distance b...

nruth/show_me_the_cookies - GitHub

Some helpers for poking around at your Capybara driven browser's cookies in integration tests.

Supports Capybara's bundled drivers (rack-test, Selenium Webdriver), and adapters for other drivers may be added.

Flexible overflow handling with CSS and JavaScript

You can use text-overflow to truncate a text using CSS but it does not fit fancy requirements.

Here is a hack for the special case where you want to truncate one of two strings in one line that can both vary in length, while fully keeping one of them. See this example screenshot where we never want to show an ellipsis for the distance:

![Flexible overflow with optional ellipsis](https://makandracards.com/makandra/5885-a-flexible-overflow-ellipsis/at...

Use CSS "text-overflow" to truncate long texts

When using Rails to truncate strings, you may end up with strings that are still too long for their container or are not as long as they could be. You can get a prettier result using stylesheets.

The CSS property text-overflow: ellipsis has been around for quite a long time now but since Firefox did not support it for ages, you did not use it. Since Firefox 7 you can!

Note that this only works for single-line texts. If you want to truncate tests across multiple lines, use a JavaScript solution like...

Mysql::Error: SAVEPOINT active_record_1 does not exist: ROLLBACK TO SAVEPOINT active_record_1 (ActiveRecord::StatementInvalid)

Possible Reason 1: parallel_tests - running more processes than features

If you run old versions of parallel_tests with more processes than you have Cucumber features, you will get errors like this in unexpected places:

This is a bug caused by multiple processes running the same features on the same database.

The bug is fixed in versions 0.6.18+.

Possib...

Using Vim to repair files with incorrect character encoding/representation

Consider you have a file that uses improper encoding on special characters. Example: You see the latin1 version "ñ" for the UTF-8 "ñ" but the file itself is stored as UTF-8 (meaning that the UTF-8 bytes are doubly encoded).

You can fix that easily with Vim:

vim broken.file

Now you tell vim that the file's encoding is actually latin1 (you can see what Vim is currently using by saying only :set fileencoding):

:set fileencoding=latin1

Write and reload the file:

:w
:e

All should be good now.

Adjust to your n...

Test whether a form field exists with Cucumber and Capybara

The step definition below lets you say:

 Then I should see a field "Password"
 But I should not see a field "Role"

Here is the step definition:

Then /^I should( not)? see a field "([^"]*)"$/ do |negate, name|
  expectation = negate ? :should_not : :should
  begin
    field = find_field(name)
  rescue Capybara::ElementNotFound
    # In Capybara 0.4+ #find_field raises an error instead of returning nil
  end
  field.send(expectation, be_present)
end

Note that you might have to adapt the step defi...

Why your javascripts should be executed after the dom has been loaded

Most of the JavaScript snippets have code that manipulates the DOM. For that reason dom manipulating javascript code should have been executed after the DOM has loaded completely. That means when the browser has finished HTML parsing and built the DOM tree. At that time, you can manipualte the DOM although not all resources (like images) are fully loaded.

The following snippets show how you can do this with plain JavaScript, jquery or prototype ([dom ready ...

How to combine greps on log files opened with tail -f

In order to chain greps on log files that are opened via tail -f test.log you have to use the --line-buffered command line option for grep.

Imagine you have the following content in your log file.

# content for log/test.log
test foo
bar
test foo bar baz
bla

Now if you would like to grep for lines that contain foo but not bar, you can use the following command chain:

$ tail -f log/test.log | grep --line-buffered "foo" | grep -v "bar"

Output:
test foo    

How to create Excel sheets with spreadsheet gem and use number formats for cells like money or date

The following snippet demonstrates how you could create excel files (with spreadsheet gem) and format columns so that they follow a specific number format like currencies or dates do.

require 'rubygems'
require 'spreadsheet'

Spreadsheet.client_encoding = 'UTF-8'

book = Spreadsheet::Workbook.new
sheet1 = book.create_worksheet :name => 'test'

money_format = Spreadsheet::Format.new :number_format => "#,##0.00 [$€-407]"
date_format = Spreadsheet::Format.new :num...

Enabling view rendering for controller specs

Views are normally (for good reason) not rendered in controller specs. If you need it to happen, use:

RSpec 1 (Rails 2):

integrate_views

RSpec 2 (Rails 3):

render_views

Note that you can't use that inside it blocks but need to put it in the nesting example group, like this:

    describe '#update' do
      cont...

colszowka/simplecov - GitHub

Code coverage for Ruby 1.9 with a powerful configuration library and automatic merging of coverage across test suites.

Note that rcov won't ever have support for Ruby 1.9, you're supposed to use rcov for 1.8 and simplecov for 1.9.

New geordi script: migrate-all

Use the command geordi migrate to migrate your databases and to prepare them before running tests. The abbrevation geordi m works as well.

  • It will run rake db:migrate if parallel_tests does not exist in your Gemfile
  • Otherwise it runs b rake db:migrate and then executes b rake parallel:prepare if parallel_tests was found in your Gemfile.

How to revert features for deployment, merge back, and how to stay sane

Removing features and merging those changes back can be painful. Here is how it worked for me.\
tl;dr: Before merging back: reinstate reverted features in a temporary branch, then merge that branch.

Scenario

Consider your team has been working on several features in a branch, made many changes over time and thus several commits for each feature.\
Now your client wants you to deploy while there are still stories that were rejected previously and can't be deployed.
...

How to organize and execute cucumber features (e.g. in subdirectories)

In cucumber you are able to run features in whatever directory you like. This also includes executing features in subdirectories. There are only some things you have to take care of.

By default, cucumber loads all *.rb files it can find (recursively) within the directory you passed as argument to cucumber.

$ cucumber # defaults to directory "features"
$ cucumber features
$ cucumber my/custom/features/dir

So, if you would like to organize features in subdirectories, you won't have *any problems when running the whole test...

Repeat an element on every printed page with CSS

Firefox, Opera and Internet Explorer will repeat elements with position: fixed on every printed page (see attached example).

The internet knows no way to do this in Webkit browsers (Chrome, Safari). These browsers will only render the element on the first printed page.

Make Makandra Consul work with RSpec 2.x and Rails 3.x

To make the RSpec matcher of the authorization solution Consul work with Rspec 2.x read the following blog post.

How to click hidden submit buttons with Selenium

In your Cucumber features you can't really click hidden elements when using Selenium (it does work for a plain Webrat scenario, though).

Unfortunately you need to hack around it, like this:

When /^I press the hidden "([^\"]+)" submit button$/ do |label|
  page.evaluate_script <<-JS
    $('input[type=submit][value="#{label}"]').show().click();
  JS
end

If your button is nested into a container that is hidden this will not do the trick. You need a more complex method to also show surrounding containers:

When /^I pre...