How to disable logging for ActiveStorage's Disk Service routes
In development, we store files using ActiveStorage's disk
service. This means that stored files are served by your Rails application, and every request to a file results in (at least!) one non-trivial log entry which can be annoying. Here is how to disable those log entries.
Example
Here is an example of what loading a single <img>
in an example application writes to the Rails log.
Started GET "/rails/active_storage/blobs/redirect/..." for ::1 at ...
Processing by ActiveStorage::Blobs::RedirectController#show as SVG
Parameter...
How the Date Header Affects Cookie Expiration and Caching
tl;dr
When a cookie includes an
Expires
attribute or an HTTP response includes caching headers likeExpires
orCache-Control
, their validity depends on the server'sDate
header if present. Otherwise, the browser uses its local time. This can lead to issues in tests with mocked time or inconsistent cache behavior.
Cookie Expires
depends on the Date
header or browser time
When a cookie includes an Expires
attribute, the browser evaluates the expiration date relative to a reference time:
- If the HTTP response ...
How to enable Rails' file_fixture helper in FactoryBot
In FactoryBot factories, Rails' file_fixture
is not available by default. To enable it, include a support module from rspec-rails:
FactoryBot::SyntaxRunner.include(RSpec::Rails::FileFixtureSupport)
That includes ActiveSupport::Testing::FileFixtures
, where file_fixture
is defined, but also configures the file_fixture_path
so that you can actually use file_fixture
.
TestProf II: Factory therapy for your Ruby tests—Martian Chronicles, Evil Martians’ team blog
Some key highlights and points from the linked article TestProf II: Factory therapy for your Ruby tests.
The Problem with Factories in Ruby Tests
- Factories are used to easily generate test data.
- However, they can unintentionally slow down test suites by creating unnecessary or excessive associated data (factory cascades).
Understanding Factory-Induced Slowdowns
- Factories often create additional data (e.g., associated records) th...
Text fragments in the browser URI fragment
Text fragments allow linking directly to a specific portion of text in a web document, without requiring the author to annotate it with an ID, using particular syntax in the URL fragment. Supporting browsers are free to choose how to draw attention to the linked text, e.g. with a color highlight and/or scrolling to the content on the page. This is useful because it allows web content authors to deep-link to other content they don't control, without relying on the presence of IDs to make that possible. Building on top of that, it could be u...
How to enable pretty IRB inspection for your Ruby class
When Ruby objects are inspected in any modern IRB, some objects (like ActiveRecord instances) are rendered with neat colors and line breaks.
You will not get that for custom classes by default -- which can be annoying if your inspection contains lots of meaningful information.
Here is what you need to do if you want your objects to be inspected nicely.
Implement a pretty_print
method
As an example, consider the following class.
class MyClass
# ...
def inspect
"#<#{self.class} attr1: #{attr1.inspect}, attr2: #{attr2...
How to eager load a single directory with Zeitwerk
Zeitwerk is the new autoloader of Rails. It is mandatory starting with Rails 7.0.
Sometimes, a model needs to know all its descendants. They might be organized in a subdirectory:
# Example
app/models/design.rb
app/models/design/light.rb
app/models/design/dark.rb
...
Now imagine that some external code needs to iterate all design subclasses.
To eager load all designs, use this line:
Rails.autoloaders.main.eager_load_dir(Rails.root.join 'app/models/design')
Make sure that app/models/design.rb
is not required manually ...
Rails: Using normalizes without copying code
Rails 7.1 added the normalizes
method which can be used to normalize user input.
It lets you define the fields you want to normalize and how to normalize them. In the example below, the Movie#title
attribute is stripped from leading and trailing whitespace automatically:
class Movie < ApplicationRecord
normalizes :title, with: -> { _1.strip }
end
Tip
Normalization lambdas are not called for
nil
values by default. To normalizenil
values, pa...
A different testing approach with Minitest and Fixtures
Slow test suites are a major pain point in projects, often due to RSpec
and FactoryBot
. Although minitest
and fixtures are sometimes viewed as outdated, they can greatly improve test speed.
We adopted a project using minitest and fixtures, and while it required some initial refactoring and establishing good practices, the faster test suite was well worth it! Stick with me to explore how these tools might actually be a good practice.
So, why is this setup faster? Partially, it's because minitest is more lightweight than RSpec
, which...
Timeouts for long-running SQL queries
While the main goal always is to prevent long-running queries in the first place, automatic timeouts can serve as a safety net to terminate problematic queries automatically if a set time limit is exceeded. This prevents single queries from taking up all of your database’s resources and reduces the need for manual intervention that might destabilize or even crash the application.
As Rails does not set a timeout on database statements by default, the following query will run for an entire day:
ActiveRecord::Base.connection.execute("S...
RSpec: Increase readability with super_diff
When handling nested hashes the RSpec output is often hard to read. Here the gem super_diff
could help.
Add super_diff to your project
- Add
super_diff
to your Gemfile:
gem 'super_diff'
- Require it in your
spec_helper.rb
require 'super_diff/rspec' # For Rails applications you can replace this with 'super_diff/rspec-rails'
-
Customize colors in
spec/support/super_diff.rb
SuperDiff.configure do |config|
config.ac...
Learn how to use ruby/debug
This talk shows simple and advanced usages of the ruby/debug debugger. It goes through a step by step debugging workflow.
Here are some command examples:
(rdbg) step 2 # step twice
(rdbg) info # show current scope, including self
(rdbg) bt # show backtrace
(rdbg) frame 3 # go directly to frame 3
(rdbg) break User#email # add a breakpoint in the email instance method
(rdbg) catch SomeException # break when SomeException is raised
Some advanced exam...
Using the ActiveSupport::BroadcastLogger
The ActiveSupport::BroadcastLogger allows you to log to multiple sinks. You know this behavior from from the rails server
command, that both logs to standard out and the log/development.log
file.
Here is an example from the ActiveSupport::BroadcastLogger
API:
stdout_logger = ActiveSupport::Logger.new(STDOUT)
file_logger = ActiveSupport::Logger.new("development.log")
broadcast = ActiveSupport::BroadcastLogger.new(stdout_logger, file_logger)
broadcast.i...
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...
A simple example with a GIN index in Rails for optimizing a ILIKE query
You can improve your LIKE
/ ILIKE
search queries in PostgreSQL by adding a GIN index with an operate class ("opclass") to split the words into trigrams to the required columns.
Example
class AddSearchTextIndexToUsers < ActiveRecord::Migration[7.1]
def change
enable_extension 'pg_trgm'
add_index :users, :search_tex...
Logging multiple lines in Rails without making filtering your logs difficult
Rails' default logger prefixes each log entry with timestamp and tags (like request ID).
For multi-line entries, only the first line is prefixed which can give you a hard time when grepping logs.
Example
Rails.logger.info(<<~TEXT)
Response from example.com:
Status: 200
Body: It works!
TEXT
With that, the following is written to your log file.
I, [2024-10-04T08:12:16.576463 #1917250] INFO -- : [97e45eae-a220-412d-96ad-e9e148ead71d] Response from example.com:
Status: 200
Body: It works!
If you then run `grep...
How to: Benchmark an Active Record query with a Ruby script
Recently I needed to benchmark an Active Record query for performance measurements. I wrote a small script that runs each query to benchmark 100 times and calculates the 95th percentile.
Note: The script requires sudo permissions to drop RAM cache of PostgreSQL. Due to the number of iterations it was impractical to enter my user password that often. And I temporary edited my /etc/sudoers
to not ask for the sudo password with johndoe ALL=(ALL) NOPASSWD: ALL
.
# Run this script with e.g. `rails ru...
Run all RSpec tests edited or added in the current branch
With this command you can run all the spec files which have been edited or added in the current branch since master:
git diff --name-only master -- ./spec | xargs -I{} rspec {}
- If you have several spec folders add them for path parameter after
./spec
accordingly. - The option
-I{}
creates a placeholder to be replaced. - You can also compare edited/added specs between commits with
<commit>..<commit>
Jasmine: Use `throwUnless` for testing-library's `waitFor`
testing-library are widely used testing utilities libraries for javascript dependent frontend testing. The main utilities provided are query methods, user interactions, dom expectations and interacting with components of several frontend frameworks, which allows us to worry less about the details happening in the browser and focus more on user centric tests instead!
Some of the time you will find a necessity to use methods like [waitFor
](https://testing-library.com/docs/dom-testing-library/api-async/...
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...
JavaScript: Listening to a class getting added
Reacting on a class getting added can be done with a mutation observer. Example:
const items = document.querySelectorAll('.item')
const expectedClass = 'active'
const activeObserver = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.target.classList.contains(expectedClass) {
// Do something
}
})
})
items.forEach(item => activeObserver.observe(item, { attributes: true, attributeFilter: ['class'] }))
Note that this is not a generic solution – it makes a few assumptions to simplif...
How to ask a (mobile) browser about the true visual viewport
The Visual Viewport API enables developers to access the actually visible area of the page. This differs from the normal viewport if:
- the user has pinch-zoomed
- the on-screen keyboard is visible
- there are other page-independent artifacts
Obtain a VisualViewport
from window.visualViewport
. The object has the properties offsetLeft
and offsetTop
, and three events: resize
, scroll
, scrollend
. You can use these to place and keep an element within the visual vi...
Avoiding Test-Case Permutation Blowout - Steven Hicks
Sometimes you want to write a test for a business rule that's based on multiple variables. In your goal to cover the rule thoroughly, you start writing tests for each permutation of all variables. Quickly it blows up into something unsustainable. With n variables for the business rule, you get 2n permutations/test cases. This is manageable with 2 variables (4 test cases), but at 3 variables (8 test cases) it becomes ridiculous, and anything beyond that feels immediately uncomfortable.
I've noticed myself using an alternate pattern for...