How to allow testing beforeunload confirmation dialogs with modern ChromeDrivers

Starting with ChromeDriver 127, if your application displays a beforeunload confirmation dialog, ChromeDriver will immediately close it. In consequence, any automated tests which try to interact with unload prompts will fail.

This is because ChromeDriver now follows the W3C WebDriver spec which states that any unload prompts should be closed automatically.
However, this applies only to "HTTP" test sessions, i.e. what you're using by default. The spec also defines that bi-directional test se...

High-level data types with "composed_of"

I recently stumbled upon the Rails feature composed_of. One of our applications dealt with a lot of addresses and they were implemented as 7 separate columns in the DB and Rails models. This seemed like a perfect use case to try out this feature.

TLDR

The feature is still a VERY leaky abstraction. I ran into a lot of ugly edge cases.

It also doesn't solve the question of UI. We like to use simple_form. It's currently not possible to simply write `f...

Jasmine: Dealing with randomness

Whenever you have to deal with randomness in a jasmine test there are some spy strategies to help you out!

Let's say we have a method Random.shuffle(array) to shuffle an array randomly and a class that uses shuffle within the constructor.

returnValue & returnValues

it('shuffles the array', () => {
  spyOn(Random, 'shuffle').and.returnValue([3, 2, 1])
  array = [1, 2, 3]
  
  testedClass = new testedClass(array)
  
  expect(Random.shuffle).toHaveBeenCalled()
  expect(testedClass.array).toEqual([3, 2, 1])
})

If you have...

How to speed up JSON rendering with Rails

I was recently asked to optimize the response time of a notoriously slow JSON API endpoint that was backed by a Rails application.
While every existing app will have different performance bottlenecks and optimizing them is a rabbit hole of arbitrary depth, I'd like to demonstrate a few techniques which could help reaching actual improvements.

The baseline

The data flow examined in this card are based on an example barebone rails app, which can be used to reproduce the r...

Ruby: Different ways of assigning multiple attributes

This card is a short summary on different ways of assigning multiple attributes to an instance of a class.

Using positional parameters

Using parameters is the default when assigning attributes. It works good for a small number of attributes, but becomes more difficult to read when using multiple attributes.

Example:

class User
  def initialize(salutation, first_name, last_name, street_and_number, zip_code, city, phone_number, email, newsletter)
    @salutation = salutation
    @first_name = first_name
    @last_name = last_nam...

Rails I18n scope for humanized attribute names

ActiveModel classes have a class method .human_attribute_name. This returns a human-readable form of the attribute:

Person.human_attribute_name(:first_name) # => "First name"

By default Rails will use String#humanize to format the attribute name, e.g. by replacing underscores with spaces and capitalizing the first word. You can configure different translation in your I18n locales, e.g. in config/locales/en.yml:

en:
  activerecord:
    attributes...

Caveat when using Rails' new "strict locals" feature

In Rails 7.1 it has become possible to annotate partials with the locals they expect:

# partial _user_name.erb
<%# locals: (user:) %>
<%= user.name %>

# view
<%= render 'user_name' %> <%# this raises an ArgumentError %>

Unfortunately, when some other code in that template raises an ArgumentError (for example an error in the User#name method) you will end up with a confusing stacktrace that looks like you have an error in your render call.

If th...

RSpec: Using helpers in view specs

If an view spec crashes due to undefined helper methods, you can enable this option:

# config/application.rb
config.action_controller.include_all_helpers = true

If you cannot use this setting, your spec can include individual helper modules like this:

describe 'some view', type: :view do
  helper SomeHelper
  helper OtherHelper

  it 'renders' do
    render 'view_that_uses_helpers'
  end
end

Alternatively you can also explicitly include *all help...

makandra cards: A knowledge base on web development, RoR, and DevOps

What is makandra cards?

We are makandra, a team of 60 web developers, DevOps and UI/UX experts from Augsburg, Germany. We have firmly anchored the sharing of knowledge and continuous learning in our company culture. Our makandra cards are our internal best practices and tips for our daily work. They are read worldwide by developers looking for help and tips on web development with Ruby on Rails and DevOps.

15 years ago – in 2009 – we wrote our first card. Since then, over 6000 cards have been created, not o...

Bookmarklet to generate a commit message for an issue in Linear.app

Your commit messages should include the ID of the issue your code belongs to.
Our preferred syntax prefixes the issue title with its ID in brackets, e.g. [FOO-123] Avatars for users.
Here is how to generate that from an issue in Linear.

Add a new link to your browser's bookmarks bar with the following URL.

javascript:(() => {
  if (document.querySelector('[data-view-id="issue-view"]')) {
    const [id, ...words] = document.title.split(' ') ;
    prompt('Commit message:', `[${id}] ${words.join(' ')}`)
  } else {
    alert('Open issue...

Unpoly + Nested attributes in Rails: A short overview of different approaches

This card describes four variants, that add a more intuitive workflow when working with nested attributes in Rails + Unpoly:

  1. Without JS
  2. With HTML template and JS
  3. With HTML template and JS using dynamic Unpoly templates
  4. Adding Records via XHR and JS

Example

For the following examples we use a simple data model where a user has zero or more tasks.

Rails: Different flavors of concatting HTML safe strings in helpers

This card describes different flavors for concatting HTML safe strings in a helper method in Rails. You might want to use the tag helper instead of the content_tag helper (the tag helper knows all self closing tags).

Example

We want to generate HTML like this:

<h1>Navigation</h1>
<ul>
  <li>Left</li>
  <li>Right</li>
</ul>

Below you ca...

How to handle when an HTML <video> element cannot autoplay

HTML <video> elements can automatically start playing when the autoplay attribute is set on them. Except for when they can not, e.g. on pageload, or when the element enters the DOM without user interaction, or when the browser for some other reason decided to not start playing the video.

While there is no native "autoplay failed" event to listen to, you can wait for video data to be loaded and then check if the video actually started playing.

Example

<video autoplay>
  <source src="example.mp4" type="video/mp4" />
</video>
...

Using rack-mini-profiler (with Unpoly)

Debugging performance issues in your Rails app can be a tough challenge.

To get more detailed insights consider using the rack-mini-profiler gem.

Setup with Unpoly

Add the following gems:

group :development do
  gem 'memory_profiler'
  gem 'rack-mini-profiler'
  gem 'stackprof'
end

Unpoly will interfere with the rack-mini-profiler widget, but configuring the following works okayish:

// rack-mini-profiler + unpoly
if (process...

Caution: rem in @media query definitions ignore your font-size

Note

Using rem only ever makes sense when the root font size is dynamic, i.e. you leave control to the user. Either by a) respecting their user agent defaults, or by b) offering multiple root font sizes in your application.

By defining @media queries in rem, they will accommodate to the root font size of your page. At a larger root font, breakpoints will be at larger widths, scaling with the font. However, there is a catch in case b) mentioned in the note above.

Relative length units in media queries are based on the initial value,...

Problems with git submodules in Gitlab CI

If you are using git submodules in Gitlab CI, you might run into a "The project you were looking for could not be found or you don't have permission to view it."

Gitlab added a feature that new projects are no longer allowed to be cloned inside CI runs of other repositories by default. To fix this

  • Go into the project used as a submodule
  • Go to "Settings" -> "CI/CD" (if you don't see this section, enable it in "Settings" -> "General" -> "Visibility, project features, permissions")
  • Go to "Token Access"
  • Either disable "Limit access to ...

Rails: Testing file downloads with request specs

tl;dr

Prefer request specs over end-to-end tests (Capybara) to joyfully test file downloads!

Why?

Testing file downloads via Capybara is not easy and results in slow and fragile tests. We tried different approaches and the best one is just okay.

Tests for file downloads via Capybara ...

  • ... are slow,
  • ... are fragile (breaks CI, breaks if Selenium driver changes, ...),
  • ... need workarounds for your specia...

Ruby on Rails: Finding a memory leak

The author describes his little journey in hunting down a memory leak. Maybe his approach and tooling may one day help you in a similar situation.

Tools: rbtrace, ObjectSpace.trace_object_allocations_start, heapy, sheap

Accessibility: Making non-standard elements interactive

A common cause of non-accessible web pages are elements that were made interactive via JavaScript but cannot be focused or activated with anything but the mouse.

❌ Bad example

Let's take a look at a common example:

<form filter>
  <input filter--query name="query" type="text">
  <span filter--reset>Clear Search</span>
</form>

The HTML above is being activated with an Unpoly compiler like this:

up.compiler('[filter]', function(filterForm) {
  const resetButton = filterForm.querySelec...

Heads up: You should always use "current_window.resize_to" to resize the browser window in tests

I recently noticed a new kind of flaky tests on the slow free tier GitHub Action runners: Integration tests were running on smaller screen sizes than specified in the device metrics. The root cause was the use of Selenium's page.driver.resize_window_to methods, which by design does not block until the resizing process has settled:

We discussed this issue again recent...

Use <input type="number"> for numeric form fields

Any form fields where users enter numbers should be an <input type="number">.

Numeric inputs have several benefits over <input type="text">:

  • On mobile or tablet devices, number fields show a special virtual keyboard that shows mostly digit buttons.
  • Decimal values will be formatted using the user's language settings.
    For example, German users will see 1,23 for <input type="number" value="1.23">.
  • Values in the JavaScript API or when submitting forms to the server will always use a point as decimal separator (i.e. "1.23" eve...

Best practices: Writing a Rails script (and how to test it)

A Rails script lives in lib/scripts and is run with bin/rails runner lib/scripts/.... They are a simple tool to perform some one-time actions on your Rails application. A Rails script has a few advantages over pasting some prepared code into a Rails console:

  • Version control
  • Part of the repository, so you can build on previous scripts for a similar task
  • You can have tests (see below)

Although not part of the application, your script is code and should adhere to the common quality standards (e.g. no spaghetti code). However, a script...

Opening a zipped coverage report with one click

Image

Tested on Ubunut 22.04

1. Opener script

  • Create a file ~/.local/bin/coverage_zip_opener with:
#!/bin/bash

tmp_folder="/tmp/coverage-report-opener"

if [ -z "$1" ]
then
 echo "Usage: coverage_zip_opener [filename]"
 exit -1
fi

if ! [[ "$1" =~ ^.*Pipeline.*Coverage.*\.zip$ || "$1" =~ ^.*merged_coverage_report.*\.zip$ ]]; then
 file-roller "$1"
 exit 0
fi

rm -Rf $tmp_folder

unzip -qq "$1" -d $tmp_folder
index_filename=$(find /tmp/coverage-report-opener -name "index.html" | ...

Element.animate() to animate single elements with given keyframes

Today I learned that you can animate HTML elements using the Web Animation API's method .animate(keyframes, options) (which seems to be Baseline for all browsers since 2022).

const fadeIn = [{ opacity: 0 }, { opacity: 1 }] // this is a keyframe example

const container = document.querySelector('.animate-me')

const animation = container.animate(fadeIn, 2000) // I am just using the animation duration as option here but it can also be given an object

// the animation object can be used for things like querying timings or stat...