Reload the page in your Cucumber features

Both these approaches will keep your GET parameters -- and will only work for GET requests.

  • Capybara:

    When /^I reload the page$/ do
      visit [ current_path, page.driver.request.env['QUERY_STRING'] ].reject(&:blank?).join('?')
    end
    
  • Webrat:

    When /^I reload the page$/ do
      visit url_for(request.params)
    end
    

For a step that distinguishes between drivers (Selenium, Rack::Test, Culerity), check [n4k3d.com](http://n4k3d.com/blog/2011/02/02/reloading-the-page-in-cucumber-with-capybara-and-seleniu...

RSpec's context method is broken

RSpec's context (which is basically an alias for describe) takes over your whole application. No object may have its own context method, or you will always receive errors like

"No description supplied for example group declared on ~/project/app/..."

The easiest workarounds:

  • do not name any method context
  • use describe instead of context in your specs, and put this into your spec_helper.rb:\
    Spec::DSL::Main.class_eval do
    if method_defined? :context
    undef :context
    end
    end

Save ActiveRecord models without callbacks or validations (in Rails 2 and Rails 3)

Rails 2

You can use

record.send(:update_without_callbacks)

or

record.send(:create_without_callbacks)

This can be used as a lightweight alternative to machinist's make or FactoryGirl's create, when you just need objects in the database but don't care about any callbacks or validations. Note that create_without_callbacks does not return the object, so you might want to do

record = Record.new.tap(&:create_without_callbacks)

Rails 3

Rails 3 no longer comes with update_without_callbacks or `crea...

Fix permissions of temporary RTeX files (which are group and world-readable)

We use RTeX for PDF exports.
While converting LaTeX to PDF, RTeX opens a temporary file which has problematic permissions: Both group and world can read those files.

Although the temp files should go away they sometimes live longer than one would expect.
We patched RTeX to fix this (and have more secure permissions). Place the code below into config/initializers/rtex.rb

Security issues with hash conditions in Rails 2 and Rails 3

Find conditions for scopes can be given either as an array (:conditions => ['state = ?', 'draft']) or a hash (:conditions => { 'state' => 'draft' }). The later is nicer to read, but has horrible security implications in some versions of Ruby on Rails.

Affected versions

Version Affected? Remedy
2.3.18 yes Use chain_safely workaround
3.0.20 no ...

Run a single example group in RSpec

To only run a single describe/context block in a long spec, you can say

spec spec/models/note_spec.rb:545

... where the describe block starts at line 545.

Note: This will only run examples that are direct children of this block, not descendants further down (when nesting describe/context blocks).

You may also pass the line of an it block to run this exact one.

How to collect a Hash from an Array

There are many different methods that allow mapping an Array to a Hash in Ruby.

Enumerable#index_by (any Rails)

users = User.all
users_by_id = users.index_by(&:id)
{
  1 => #<User id: 1, name: "Alice">,
  2 => #<User id: 2, name: "Bob"> 
}

In case of a duplicate, the last entry wins.

Enumerable#group_by (Ruby 1.8.7+)

Use group_by when duplicates are possible.
Hash values are always an Array of elements per group.

users = User.all
users_by_nam...

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

Strip carriage returns in submitted textareas

When submitting textareas, browsers sometimes include carriage returns (\r) instead of just line feeds (\n) at the end of each line. I don't know when this happens, and most of the time it doesn't matter.

In cases where it does matter, use the attached trait to remove carriage returns from one or more attributes like this:

class Note
  does 'strip_carriage_returns', :prose, :code
end

Here is the test that goes with it:

describe Note do

  describe 'before_validation' do...

Fix a spec that only runs when called directly

When a spec only runs when it is called directly, but not as part of the whole test suite, make sure the filename is foo_spec.rb instead of just foo.rb.

Know your Haml comments

There are two distinct ways of commenting Haml markup: HTML and Ruby.

HTML comments

This will create an HTML comment that will be sent to the client (aka browser):

/= link_to 'Example', 'www.example.com'

This produces the following HTML:

<!-- = link_to 'Example', 'www.example.com' -->

Only use this variant if you need the comment to appear in the HTML.

Ruby comments

This will comment code so it will not be sent to the client:

-# = link_to 'foo'

99% of the time you'll be adding notes f...

Debug Ruby code

This is an awesome gadget in your toolbox, even if your test coverage is great.

  • gem install ruby-debug (Ruby 1.8) or gem install debugger (Ruby 1.9)
  • Start your server with script/server --debugger
  • Set a breakpoint by invoking debugger anywhere in your code
  • Open your application in the browser and run the code path that crosses the breakpoint
  • Once you reach the breakpoint, the page loading will seem to "hang".
  • Switch to the shell you started the server with. That shell will be running an irb session where you can step thr...

Override e-mail recipients in ActionMailer

Our gem Mail Magnet allows you to override e-mail recipients in ActionMailer so all mails go to a given address.

This is useful for staging environments where you want to test production-like mail delivery without sending e-mails to real users.

Use Shoulda's validate_uniqueness_of matcher correctly

This raises "Could not find first Keyword":

describe Keyword do
  it { should validate_uniqueness_of(:text) }
end

Do this instead:

describe Keyword do

  it 'should have a unique #text' do
    Keyword.make
    should validate_uniqueness_of(:text)
  end

end

This is the intended behavior.

Automatically run bundle exec if required

There will probably be better solutions as we become more experienced with using Bundler, and more command line tools become Bundler-aware.

b will use bundle exec if there is a Gemfile in the working directory, and run the call without Bundler otherwise.

b spec spec

This script is part of our geordi gem on github.

Airbrake notification in Rake tasks

Put

def task_with_hoptoad_notification(options)
  task(options) do
    begin
      yield
    rescue Exception => e
      Airbrake.notify(e)
      raise e
    end
  end
end

at the top of the Rakefile, and replace all relevant

task :my_task => :environment do
    do_something
end

with

task_with_hoptoad_notification :my_task => :environment do
    do_something
end

This will use the usual notification rules, i.e. you won't get anything in the development or test environments.
...

Bundler for Rails 2.3.x

Update RubyGems and Passenger

Bundler requires Rubygems >= 1.3.6. Run gem update --system if you have an older version.
It also is not compatible with older versions of passenger, so bring that up to date as well (2.2.15 works).

If you installed RubyGems through apt (which you should never do!), you may see a message giving you a hint to use apt to update.
Some people advise to install the 'rubygems-update-1.3.7' gem on Ubuntu systems if you used apt to install RubyGems.
I did that - and lost all...

Preload associations in loaded records

Sometimes you want to fetch associations for an ActiveRecord that you already loaded, e.g. when it has deeply nested associations.

Edge Rider gives your models a static method preload_associations. The method can be used to preload associations for loaded objects like this:

class UsersController < ApplicationController
  def show
    @user = User.find(params[:id])
    @user.preload_associations(threads: { posts: :author }, messages: :sender)
  end
end

The attached initializers re...

Spec correct routing of custom URLs

When you roll custom URLs with hacks like routing-filter, you can put a spec like this into spec/routing/routing_spec.rb:

Test e-mail dispatch in Cucumber

Spreewald has steps that let you test that e-mails have been sent, using arbitrary conditions in any combination.

The attached file is for legacy purposes only.