Use Memoizer instead of ActiveSupport::Memoizable

ActiveSupport::Memoizable will be removed from Rails and has a lot of strange caveats that will ruin your day.

Use the Memoizer gem instead. It works in all past and future Railses and has none of the annoying "features" of ActiveSupport::Memoizable. It just does memoization and does it well.

The syntax is similiar also:

class Foo
  include M...

Do not use "find" on Capybara nodes from an array

In a nutshell: Capybara's find will not work properly on nodes from a list. Don't find on elements from a list.

Background

Consider this HTML:

<div class="message">
  <h2>Hello World</h2>
  Lorem ipsum...
</div>
<div class="message">
  <h2>Hello Universe</h2>
  Lorem ipsum...
</div>

Now let's say you obtain a list of all such message containers as an array:

messages = page.all('.message')

And then you look at their titles like this:

messages[0].find('h2').text
=> "Hello W...

Rails 2's CookieStore produces invalid cookie data, causing tests to break

Note that this seems to affect only recent Rails 2 versions.

You will not encounter this until you are writing to the cookie more than once, but when doing so, integration tests (Cucumber) may break for you with this error:

You have a nil object when you didn't expect it!
You might have expected an instance of ActiveRecord::Base.
The error occurred while evaluating nil.[] (NoMethodError)

Background

The regular/short cucumber backtrace is not of any help but looking at the full trace reveals that ActionPack's `actio...

Security fixes for Rails 2.3

Last week saw a security issue with rails 2.3 that required a fix. While an official patch was provided, the 2.3 branch is no longer maintained. So we forked it.

(I'm sure there are already 100 other forks doing absolutely the same, but they are not very easily discoverable.)

To use our fork, change the gem "rails"... line in your Gemfile to this:

gem 'rails', :git => 'https://github.com/makandra/rails.git', :branch => '2-3-fixes'

The intent is to make as few changes to the f...

Fix: Capybara is very slow when filling out fields in large forms

In large forms (30+ controls) new Capybara version become [extremely slow] when filling out fields. It takes several seconds per input. The reason for this is that Capybara generates a huge slow XPath expression to find the field.

The attached code patches fill_in with a much faster implementation. It's a dirty fix and probably does a lot less than Capybara's own fill_in so don't use it unless you are having problems with test suites that are unusable because of this...

Rails asset pipeline: Why relative paths can work in development, but break in production

The problem

When using the asset pipeline your assets (images, javascripts, stylesheets, fonts) live in folders inside app:

app/assets/fonts
app/assets/images
app/assets/javascripts
app/assets/stylesheets

With the asset pipeline, you can use the full power of Ruby to generate assets. E.g. you can have ERB tags in your Javascript. Or you can have an ERB template which generates Haml which generates HTML. You can chain as many preprocessors as you want.

When you deploy, Rails runs assets:precompile...

Linux: How to add a task bar to VNC displays

If you are using VNC to run Selenium tests, it may be hard to see what's going on since by default there is no list of open windows and Alt+Tab won't work.

Solving that is easy:

  1. Install a panel of your choice (like lxpanel) which offers task switching:

    sudo apt-get install lxpanel
    

    (You can't use gnome-panel because it won't start twice -- but lxpanel does a good job)

  2. To have that panel appear on VNC screens by default, edit ~/.vnc/xstartup...

Visualized introduction how git works

Quick introduction to git internals for people who are not scared by words like Directed Acyclic Graph.


The linked page offers a simple yet concise explanation of how git is organized internally ('a directed acyclic graph with post-it notes'). Each feature is illustrated by a simple diagram, so you get a sound understanding of how each command affects git's structure.

Plotting graphs in Ruby with Gruff

Geoffrey Grosenbach has created Gruff for easily plotting graphs. It is written in pure Ruby and integrates with Rails applications.

It provides features as automatic sizing of dots and lines (the more values, the thinner the graph's elements), custom or predefined themes, different styles (bar, line, dot and many more) and multiple graphs in one chart.

Installation

In your Gemfile:

gem 'rmagick', :require => false
gem 'gruff'

Then run bundle install (and don't forget to restart your development server.)

Usage

This i...

Use a special version of Chrome for selenium (and another for your everyday work)

Sometimes you need a special version of chrome because it has some features you need for testing, like in this card. You do not need to use that Version apart from tests, because you can tweek selenium to use a special version that you set in your environment:

# features/support/chrome.rb
require "selenium/webdriver"

Capybara.register_driver :chrome320x480 do |app|
  
  if driver_path = ENV["CHROME_SELENIUM_BIN...

Set the accept-language of Chrome in selenium tests

You can set the resolution and user agent used in selenium tests with chrome with the method described in this card, but you can also set the accept-language and other profile settings if you do this:

# features/support/chrome.rb
require "selenium/webdriver"


Capybara.register_driver :chrome320x480 do |app|
  args = []
  args << "--window-...

Run Chrome in a specific resolution or user agent with Selenium

When you want to test how an web-application reacts in a specific resolution, you can set up a specific Selenium driver for some tests:

 Before('@chrome320x480') do
     Capybara.current_driver = :chrome320x480
 end

 After('@chrome320x480') do
    Capybara.use_default_driver 
 end

You can use either chromium or chrome beta (as of 2012.05 the Version "19.0.1084.41 beta" works), or any other member of the family. It only needs to supports the "--window-size" command-line switch. [See this list](http://peter.sh...

Navigating through the browser history in a cucumber feature using selenium

In order to navigate through the browser history. you can manipulate the window.history object via javascript like follows:

When /^I go back in the browser history$/ do
  page.evaluate_script('window.history.back()')
end 

For further functions of the window and history objects check out this link.


An improved version of this step is now part of our gem spreewald on Github.

Browser support for box-shadow

Basic box shadow support is available in all browsers today, but you need to check to which extend they are supported. Implementations differ:

  • Are multiple box shadows (separated by comma) possible?
  • Are inset shadows possible?
  • Can the spread radius be defined?
  • Can you use it without vendor prefix?

A good compatibility chart can be found here. The gist is that, except for IE and some Safaris, you can use all features ...

Fix warning: Cucumber-rails required outside of env.rb

After installing Bundler 1.1 you will get the following warning when running tests:

WARNING: Cucumber-rails required outside of env.rb. The rest of loading is being defered until env.rb is called.\
To avoid this warning, move 'gem cucumber-rails' under only group :test in your Gemfile

The warning is misleading because it has nothing to do with moving cucumber-rails into a :test group. Instead you need to change your Gemfile to say:

gem 'cucumber-rails', :require => false

validates_acceptance_of is skipped when the attribute is nil

validates_acceptance_of :terms only works if terms is set to a value. The validation is skipped silently when terms is nil.

While this behavior is useful to validate acceptance in the frontend and not the admin backend, it also makes it very easy to unintentionally skip the validation altogether by forgetting to add the checkbox to a form. E.g. validates_acceptance_of :terms_with_typo will be skipped silently even if there is no column with t...

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 calling page.find(...). This way the behavior is only changed for this one find 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...

Hack-fix Selenium::WebDriver::Element#select is deprecated

In some older Capybara versions (e.g. 0.3.9), we're getting lots of deprecations warnings:

Selenium::WebDriver::Element#select is deprecated. Please use Selenium::WebDriver::Element#click and determine the current state with Selenium::WebDriver::Element#selected?

Hani-elabed on Github helps. Add this code to features/support/env.rb to remove them temporarily:

# June 30th, 2011
# a temporary hack to disable the annoying upstream warnings capybara > selenium-webdriver 0.2.2
# capybara folks know about this and are working on it. S...

Customize path for Capybara "show me the page" files

When you regularly make use of Cucumber's "show me the page" step (or let pages pop up as errors occur), the capybara-20120326132013.html files will clutter up your Rails root directory.

To tell Capybara where it should save those files instead, put this into features/support/env.rb:

Capybara.save_and_open_page_path = 'tmp/capybara'

Fix [RubyODBC]Cannot allocate SQLHENV when connecting to MSSQL 2005 with Ruby 1.8.7. on Ubuntu 10.10

I followed this nice guide Connecting to MSSQL with Ruby on Ubuntu - lambie.org until I ran in the following errors:

irb(main):001:0> require "dbi"; dbh = DBI.connect('dbi:ODBC:MyLegacyServer', 'my_name', 'my_password')

DBI::DatabaseError: INTERN (0) [RubyODBC]Cannot allocate SQLHENV
  from /usr/lib/ruby/1.8/dbd/odbc/driver.rb:36:in `connect'
  from /usr/lib/ruby/1.8/dbi/handles/driver.rb:33:in `connect'
  from /usr/lib/ruby...

Linux: Mount second encrypted HDD automatically without entering a password

This is one possibility to do this. There are other and maybe even better ways to do this.

  1. Generate a key for your encrypted harddisk:

    dd if=/dev/random of=/home/bob/keyfile_sdb1 bs=4096 count=1
    
  2. Then add your keyfile to encrypted harddisk: How to change your dm-crypt passphrase (step 3)

  3. Create a mountpoint:

    mkdir /mnt/space
    
  4. Create a script e.g. in your homedirectory (/home/bob/mount_sdb1.sh):

    #!bin/bash
    
    ...
    

Capybara: Test that a string is visible as static text

This is surprisingly difficult when there is a <textarea> with the same text on the page, but you really want to see the letters as static text in a <p> or similiar.

The step definition below lets you say:

Then I should see the text "foo"

You should not look too closely at the step definition because when you see the light, it will blind you.

Then /^I should see the text "(.*?)"$/ do |text|
  elements = page.all('*', :text => text).reject { |element| element.tag_name == 'textarea' || element.all('*', :text => text...

Spec "content_for" calls in helpers

This only applies to RSpec below version 1.3.2. The issue has been fixed in RSpec 1.3.2, and most likely RSpec 2 and later versions.


When you have a helper that calls content_for and want to check its behavior you should probably write a feature instead. If you still want to do it, mind the following.

Consider this helper:

module LayoutHelper
  def title(string)
    content_for :title, string
    string
  end
end

Somewhere in the layout we'd then say something like this: `<%= yield :title %...</p>