How to: Solve gem loaded specs mutex

Use bundler > 1.15 to fix Gem::LOADED_SPECS_MUTEX (NameError).


Given the following project:

ruby -v
ruby 1.8.7

bundler -v
Bundler version 1.13.7

gem -v
1.8.30

rails -v
Rails 3.2.22.1

Running specs or features resulted in:

uninitialized constant Gem::LOADED_SPECS_MUTEX (NameError)

The previous settings described in Maximum version of Rubygems and Bundler for Ruby 1.8.7 and Rails 2.3 (even the rails version was rails 3.2 and not 2.3) seems not to work here, so I used (also described in the ca...

List of :status symbols for rendering in Rails

When your Rails controller calls render, you can pass a :status option for the HTTP status code:

render 'results', status: 400

All important status codes also have a symbol alias, which makes your code easier to read:

render 'results', status: :bad_request

Attached is a list of available symbol values for :status.

How to stub class constants in RSpec

Hint: There's another card with this helper for Cucumber features.


Sometimes you feel like you need to stub some CONSTANT you have defined in an other class. Since actually constants are called constants because they're constant, there's no way to easily stub a constant.

Here are three solutions for you.

Easiest solution

Rethink! Do you really need CONSTANT = %w[foo bar] to be constant? In many cases, setting it as a...

How to control Chromedriver using curl

Here is how to use Chromedriver without libraries like selenium-webdriver. This can be useful for debugging.

The following example visits a web page and reads the a headline's text contents.

  1. Create a session. You will get a JSON response containing lots of information about your Chrome session, including a sessionId. Use that to send any future commands to your chromedriver session.

    $ curl -XPOST http://localhost:9515/session -d '{"desiredCapabilities":{"browserName":"chrome"}}'
    {"sessionId":"your-session-id-here","sta...
    

Ruby: Removing leading whitespace from HEREDOCs

If you're on Ruby 2.3+ there's a <<~ operator to automatically unindent HEREDOCs:

str = <<~MESSAGE
  Hello Universe!
  This is me.
             Bye!
MESSAGE

If you have an older Ruby, you can use the String#strip_heredoc method from ActiveSupport. See Summarizing heredoc in ruby and rails for an example.

Technically...

Chrome: Making high-resolution website screenshots without add-ons

If you want to make a screenshot of a website that works well in print or on a high-DPI screen (like Apple Retina displays), here is how you can capture a high-resolution screenshot.

You can do this without an addon:

  • Open the website
  • If you have multiple monitoros:
    • Resize the Chrome window so it covers multiple monitors (in Linux you can hold ALT and resize by dragging with the right mouse button)
    • Zoom into the page using CTRL + and CTRL - so it covers most of the window area. Leave a little padding on the left and right so...

RSpec expects pending tests to fail

When flagging a spec that will be implemented later as pending, include a failing spec body or RSpec 3 will consider the pending test as failing.

The reasoning is: If the spec is flagged as pending but passes, it should not be pending. So these will fail:

it 'does something' do
  pending
end

it 'does something else' do
  pending
  expect(1).to eq(1)
end

The first case may be unexpected, if you just wanted to write down that something should eventually happen that will be implemented later.

Instead, ...

Heads up! Years are always floats in Rails < 4

Watch out when saying something like 1.year in Rails. The result is not a Fixnum and can cause unexpected errors when the receiving end expects a Fixnum.

While anything from seconds to months are Fixnums, a year is a Float in Rails -- when called on a Fixnum itself:

>> 10.seconds.class
=> Fixnum
>> 2.minutes.class
=> Fixnum
>> 24.hours.class
=> Fixnum
>> 28.days.class
=> Fixnum
>> 9.months.class
=> Fixnum
>> 1.year.class
=> Float # Boom.

While they are [technically correct](http:...

Centering with CSS vertically and horizontally (all options overview)

There are a million ways to center <div>s or text in CSS, horizontally or vertically. All the ways are unsatisfying in their own unique way, or have restrictions regarding browser support, element sizes, etc.

Here are two great resources for finding the best way of aligning something given your use case and browser support requirements:

How to center in CSS

A long form that lets you define your use case and browser support requirements, then shows you the preferred way of aligning.

[Centering CSS: A co...

Think twice before using application names in your variables and methods

I recently had fun with replacing a custom video plattform ("mycustomtv") in one of our applications. I learned a lot about naming stuff.

youtube_mycustomtv_chooser is a bad name for a directive.

Why?

  • if you add, for example, other video systems like vimeo, the name of the method either lies or will get longer.
  • if you replace one system, you will have to change the method and all of its occurrences (and you're very lucky if it is only one poorly named thing in your application)

What would be a better solution?

Abstract fro...

Katapult 0.4.0 released

Features

  • Generating a project README
  • Finally: Support for modelling associations between models in your application model! Example:
# lib/katapult/application_model.rb

model 'Cart' do |cart|
  cart.belongs_to 'User'
end

crud 'User' do |user|
  user.attr :fullname
end

Cucumber: How to avoid VCR errors for unused requests in pending tests

When you have a pending Cucumber step (or feature) that also uses an existing VCR cassette, your pending test may fail at the very end with an error like this:

There are unused HTTP interactions left in the cassette:
  - [get ...] => [200 ...]
  - [get ...] => [200 ...] (VCR::Errors::UnusedHTTPInteractionError)

The error happens because your VCR is configured to complain about cassettes that contain extra requests which your test did not use. This is often a good configuration.
If you do not want to change your whole test suite...

Katapult 0.3.0 released

Katapult 0.3.0 brings Rails 5 and Ruby 2.5 support with a new design, plus a ton of smaller features, fixes and improvements.

Features

  • Generating a Rails 5.1.4 app on Ruby 2.5.0
  • Dropped asset pipeline in favor of Webpacker
  • The generated application now has a sleek, simple design based on Bootstrap
  • Employing Unpoly
  • New application model DSL shortcut crud for "create a model and a web UI with crud actions"
  • The generated application model is now a transformable e...

Ruby: Using all? with empty collection

Enumerable#all? returns true for an empty collection. This totally makes sense but you have to think about it when making assumptions on relations which might be empty.

[].all?(&:will_never_be_called_here) => true

Example with empty collection

class Researcher < ActiveRecord::Base
  has_many :papers
end

class Paper
  validates :topic, inclusion: { in: ['computer_science', 'mathematics', 'economy'] }
end

Easy goal: Delete all researches who write onl...

How to mirror a git repo to a new remote

Say you want to move a git repository from one remote (perhaps Github) to another (perhaps Gitlab).

If you have the repo checked out, you still should make sure to mirror all branches of the old remote, not only those you happen to have checked our. Otherwise the target repo will become a copy of your current repo, and not the source repo, potentially missing commits. You can use this:

git remote rename origin old-origin
git remote add origin <new-remote>
git fetch old-origin --prune
git push --prune origin +refs/remotes/old-origin/*:r...

How to: Run webpack dev server with vcap.me

If your Rails application is using Webpack you need to serve assets on the same host as you application runs, otherwise you will see the following errors in your browser console:

[WDS] Disconnected!
Invalid Host header

So if you are using awesome.vcap.me:3000 you need to start the webpack-dev-server with a different host than localhost (0.0.0.0):

bin/webpack-dev-server --host awesome.vcap.me

Capybara: A step for finding images with filename and extension

This cucumber step is useful for testing an image (looking at the src of the image).

Then(/^I should see the image "([^"]*)"$/) do |filename_with_extension|
  expect(page).to have_css("img[src*='#{filename_with_extension}']")
end
Then I should see the image "placeholder.png"

Outline: Read more about how to test a uploaded file here, e.g. file downloads.

How to debug Rails autoloading

ActiveSupport::Dependencies takes care of auto-loading any classes in development. This is usually useful, but when you run into issues with the Rails autoloader, you should take a look at what it's doing.

For me this was useful in an "exciting" case of auto-loading classes inside a thread which caused the application to stop responding.

Rails 4.x

ActiveSupport::Dependencies includes logging support. It is easy to use:

ActiveSupport::Dependencies.logger = Rails.logger

Rails 5+

[Logging support was removed](https://github...

PostgreSQL: How to UPDATE multiple attributes with multiple joins

This is an extension to PostgreSQL vs MySQL: How to UPDATE using a JOIN.

UPDATE employees
SET department_name = departments.name,
  department_area = areas.name
FROM departments, areas
WHERE employees.department_id = departments.id
AND departments.id = areas.department_id

About-Payments: Platform to compare payment providers

About-Payments is here to help you to accept payments online and
find the best payment service provider for your e-commerce business.

Sprites with Compass

Using CSS sprites for background images is a technique for optimizing page load time by combining smaller images into a larger image sprite.

There are ongoing arguments on how useful this still is, as modern browsers become more comfortable to load images in parallel. However, many major websites still use them, for example amazon, [facebook](...

How to query PostgreSQL's json fields from Rails

PostgreSQL offers a really handy field type: json. You can store any JSON there, in any structure.

While its flexibility is great, there is no syntactic sugar in Rails yet. Thus, you need to manually query the database.

Demo

# Given a Task model with 'details' json column
Task.where("details->>'key' = ?", "value") # matches where 'details' contains "key":"value"
Task.where("details->>'{a,b}' = ?", "value") # matches where 'details' contains "a":{"b":"value"}
Task.where("details->'a'->>'b' = ?", "value") # same as above, but vi...

Font Awesome 5 migration guide

Font Awesome version 5 changed some icon names, and introduces new prefixes fab, far, and fas.

There is a JavaScript shim that you can use as a "quick fix". It allows you to keep v4 icon names on v5.

The linked page includes details on using that, and a migration guide including a list of icon renames.

RSpec: How to check that an ActiveRecord relation contains exactly these elements

To check which elements an ActiveRecord relation contains use the contain_exactly matcher.

describe User do
  let!(:admin) { create(:user, role: 'admin') }
  let!(:customer) { create(:user, role: 'customer') }
  
  subject(:users) { User.where(role: 'admin') }
  
  # Recommended (The error output is most helpful)
  it { expect(users).to contain_exactly(admin) }
  
  # Other options
  it { expect(users).to eq([admin]) }
  it { expect(users.pluck(:id).to eq([admin.id]) }
end

In case you have an `ActiveRecord::AssociationRelati...