Archive for March, 2012

Simplify your conditional step definitions with should_unless

Friday, March 23rd, 2012

In cucumber, you often want to be able to use a step in both it’s positive and negative form. For example, in different universes I might want to ensure that “pigs can fly”, or that “pigs can not fly”. Typically I’ve either written two step matchers for this, or added an awkward conditional:

Then /^pigs can (not |)fly$/ do |negated|
  if negated.blank?
    Pig.new.should have_the_power_of_flight
  else
    Pig.new.should_not have_the_power_of_flight
  end
end

But today I decided to factor that out into a little helper method in my cucumber config:

# features/support/env.rb
class Object
  def should_unless(missing, matcher)
    missing.match(/not/) ? should_not(matcher) : should(matcher)
  end
end

This allows me to write my matcher much more simply:

Then /^pigs can (not |)fly$/ do |negated|
  Pig.new.should_unless negated, have_the_power_of_flight
end

So fresh and so DRY!

Memcache on Rails with Dalli not expiring

Thursday, March 15th, 2012

This was a little bit of a stumper. In testing, when I tried to cache objects in Memcache with Dalli, by setting expires_in to, say, 5.seconds, the cache didn’t seem to expire.

After debugging into Dalli, I now see why:

# dalli-1.1.4/lib/active_support/cache/dalli_store.rb:131
if expires_in > 0 && !options[:raw]
  # Set the memcache expire a few minutes in the future to support race condition ttls on read
  expires_in += 5.minutes
end

Dalli adds 5 minutes to the expires_in for all cache writes.