4018 cards

RSpec: How to turn off partial double verification temporarily

With RSpec 3.6.0 you can turn of partial double verification for single mocks. This might be handy in case you are testing helpers in Rails, where you sometimes rely on methods defined in the application controller (e.g. current_user and current_power).


class ApplicationController

  def current_user


module UsersHelper

  def user_display_name
    [current_user.first_name, current_user.last_name].join(' ')


Unit test with error

describe UsersHelper ...

Ruby tempfiles

Tempfiles get deleted automatically

With the the ruby Tempfile class you can create temporary files. Those files only stick around as long as you have a reference to those. If no more variable points to them, the GC may finalize the object at some point and the file will be removed from the filesystem. If you would try to access your tempfile then using its path (which you stored previously), you would get an error because the file no longer exists.

Unlink your tempfiles when you're done with them

How to show jQuery event handler on element

Chrome gives you the currently selected element in the inspector with $0. If you select a button in the DOM you can set and inspect the event handler with the following two code lines:

$($0).on('click', function() { console.log('Hello') })
jQuery._data($0, "events").click[0].handler
// => "function () { console.log('Hello') }"

This is useful for debugging.

When upgrading/downgrading RubyGems and Bundler on a server, you must clear bundled gems

On application servers, gems are usually bundled into the project directory, at a location shared across deployments.

This is usually shared/bundle inside your project's root directory, e.g. /var/www/your-project/shared/bundle/.
If you can't find that, take a look at current/.bundle/config and look for BUNDLE_PATH.

When you are changing the version of RubyGems or Bundler on a system where gems are installed this way, you must wipe that bundle directory in addition to the user and system gems or gems that are already ins...

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:


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


How to make RubyMine aware of Cucumber steps defined in gems

If your Ruby project includes a gem like Spreewald Archive that comes with some external step definition, RubyMine does not know about them by default and will highlight the step as an undefined reference:


To link these external step definitions to RubyMine, add the corresponding gems to your RubyMine-Settings:

  • Go to Settings (ctrl + alt + s)
  • Go to Languages and Frameworks
  • Go to Cucumber
  • There, add your gem (e.g "spreewald") via the little "+" from the b...

RSpec: How to define classes for specs

RSpec allows defining methods inside describe/context blocks which will only exist inside them.
However, classes (or any constants, for that matter) will not be affected by this. If you define them in your specs, they will exist globally. This is because of how RSpec works (short story: instance_eval).

describe Notifier do
  class TestRecord
    # ...
  let(:record) { TestRecord.new }
  it { ... }

# TestRecord will exist here, outside of the spec!

This will come bite you at least when you try to define a clas...

Flexbox: How to prevent <pre> elements from overflowing

I recently had the problem that embedded code boxes crashed my layout.

It turned out that pres break out of their containers when using them inside a deeper nested flex layout.
For me it was a flex inside a flex item (fleXzibit).


<div class="flex">
  <div class="flex-item">
    <div class="nested-flex">
      <div class="nested-flex-item">
        <pre>A code example</pre>

The reason is that flexbox items default to `mi...

JavaScript: New Features in ES2021


With ES2021 you now can use str.replaceAll(), Promise.any(), logical assignment operators, numeric separators and WeakRef on all major browsers except IE11.


JavaScript's replace(searchValue, replaceValueOrFn) by default replaces only the first match of a given String or RegExp.
When supplying a RegExp as the searchValue argument, you can specify the g ("global") modifier, but you have to remember doing that, hence using replace when you expect global replacement is prone to errors.
When supplying st...


Rails: how to write custom email interceptors

Nowadays it is fairly easy to intercept and modify mails globally before they are sent. All you have to do is register an interceptor class which responds to .delivering_email(message). This card will show you two common use cases.

Subject prefix:

Usually you want to prefix the subject line of emails with the current environment (except production) so you can differentiate between production mails and mails from other environments. Of course a prefix can be set directly in the mailer, however, it is safer and cleaner to d...


Inspect the page content in a Cucumber session

When you need to see the content of a page (i.e. not all the HTML but the relevant text body)

  • you can do pp (html_content)
    • pp will format the html String human readable pretty printed
  • where html_content can be replaced by one of the following commands:


body or response.body


  • page.driver.html.content
  • page.body



The returned strings can be cleaned up by calling .gsub(/^\s*$/, '').squeeze("\n") on them.\
Although this may be useful for d...


Understanding race conditions with duplicate unique keys in Rails

validates_uniqueness_of is not sufficient to ensure the uniqueness of a value. The reason for this is that in production, multiple worker processes can cause race conditions:

  1. Two concurrent requests try to create a user with the same name (and we want user names to be unique)
  2. The requests are accepted on the server by two worker processes who will now process them in parallel
  3. Both requests scan the users table and see that the name is available
  4. Both requests pass validation and create a user with the seemingly available name...

Don't require files in random order

A common pattern in Ruby is to to require all files in a specific diretory, using something like

Dir.glob(Rails.root.join('lib/ext/**/*.rb')).each do |filename|
  require filename

However, this causes files to be required in an order determined by the file system. Since load order can be important, this may lead to different behavior on different machines which are hard to debug.

Simply add a .sort:

Dir.glob(Rails.root.join('lib/ext/**/*.rb')).sort.each do |filename|
  require filename

Ruby 3

Ruby ...


Unpoly: Automatically show the full better_errors page when Rails raises an error

When an AJAX request raises an exception on the server, Rails will show a minimal error page with only basic information. Because all Unpoly Archive updates work using AJAX requests, you won't get the more detailled better_errors Archive page with the interactive REPL Archive .

Below is an event listener that automatically repeats the request as a full-page load if your development error shows an error page. This means you get...


Getting different results working with SVG files and ImageMagick

When you are working with SVG files and ImageMagick you can get different results on different machines depending on which additional packages you have installed.

From: http://www.imagemagick.org/script/formats.php Archive

ImageMagick utilizes inkscape if its in your execution path otherwise RSVG. If neither are available, ImageMagick reverts to its internal SVG renderer.

Use DatabaseCleaner with multiple test databases

There is a way to use multiple databases Archive in Rails.
You may have asked yourself how you're able to keep your test databases clean, if you're running multiple databases with full read and write access at the same time. This is especially useful when migrating old/existing databases into a new(er) one.

Your database.yml may look like this:

default: &default
  adapter: postgresql
  encoding: unicode
  username: <%= ENV['DATABASE_USER'] %>
  host: <%= ENV['DATABASE...

ActiveRecord: Query Attributes

You can use attribute? as shorthanded version of attribute.present?, except for numeric attributes and associations.

Technical Details

attribute? is generated for all attributes and not only for boolean attributes.

These methods are using #query_attribute under the hood. For more details you can see ActiveRecord::AttributeMethods::Query.

In most circumstances query_attribute is working like attribute.present?. If your attribute is responding to :zero? then you have to be aware that `query_attri...

How to bind an event listener only once with Unpoly

You can use Unpoly's up.on Archive with a named listener function and immediately unbind this event listener with { once: true }:

up.on('up:fragment:inserted', { once: true }, function () { ... })

In Unpoly 1 you can immediately unregister the listener with up.off Archive :

up.on('up:fragment:inserted', function fragmentInsertedCallback() {
  up.off('up:fragment:inserted', fragmentInsertedCallback)
  // ... code for the callback function, which should run only once

Example ...

This website uses short-lived cookies to improve usability.
Accept or learn more