This Week in #dev (Feb 9, 2024)

Welcome to another edition of This Week in #dev, a series of posts where we bring some of our most interesting Slack conversations to the public.

Inverting where Clauses in Rails

Fer Perales learned about the invert_where method in Rails’ Active Record.

class User
  scope :active, -> { where(accepted: true, locked: false) }
end

User.active
# WHERE `accepted` = 1 AND `locked` = 0

User.active.invert_where
# WHERE NOT (`accepted` = 1 AND `locked` = 0)

Jest’s test.each Global

Stefanni Brasil shared a TIL about Jest’s test.each global. Use it if you keep duplicating the same test suites with different data. test.each allows you to write the test suite once and pass data in.

Here’s a simple example using the table syntax:

test.each`
  a    | b    | expected
  ${1} | ${1} | ${2}
  ${1} | ${2} | ${3}
  ${2} | ${1} | ${3}
`('returns $expected when $a is added to $b', ({a, b, expected}) => {
  expect(a + b).toBe(expected);
});

SQL ALL and ANY

SQL’s ALL and ANY were this week’s learning from Mike Burns. These operators allow you to compare a value with all values in a set returned by a subquery.

For instance, if you want to find all authors who have only published books, you could use the following SQL query:

SELECT authors.*
FROM authors
WHERE 'published' = ALL (
  SELECT status
  FROM books
  WHERE author_id = authors.id
);

Less Logs, More Speed in Your Tests

Sarah Lima learned about unlogged tables in PostgreSQL. They can improve write performance by preventing tables from generating WAL (Write Ahead Log) information. You can enable this on your tests to improve performance:

# config/environments/test.rb

ActiveSupport.on_load(:active_record_postgresqladapter) do
  self.create_unlogged_tables = true
end

Here are some other non-durable PostgreSQL settings which can help us trade off durability for performance.

Thanks

This edition was brought to you by Fer Perales, Mike Burns, Sarah Lima, and Stefanni Brasil. Thanks to all contributors! 🎉