← Back to blog

Comparing ActiveRecord attributes to a Hash in Rails Tests: slice, symbolize, and the Types That Bite

· Lachlan Young

The failure everyone hits once

You create a record, you build the hash you expect, and you write the obvious assertion:

user = User.create!(name: "Ada", email: "ada@example.com", role: :admin)

expected = { name: "Ada", email: "ada@example.com", role: "admin" }

assert_equal expected, user.attributes

It fails, and the diff is a wall of noise. user.attributes has an id, created_at, updated_at, and every column you did not mention. Worse, even if you strip those, the keys are strings, not symbols, so the hashes are never equal. Ruby compares { name: "Ada" } and { "name" => "Ada" } as different hashes, and rightly so.

This is one of the most common reasons a Rails test fails for a reason that has nothing to do with the code under test. The fix is to be deliberate about what you are comparing and what shape it is in.

Step one: compare only what you care about

Almost always, you do not want to assert on the whole attribute set. You want to assert on the fields the code under test is responsible for. Hash#slice does exactly this:

actual = user.attributes.slice("name", "email", "role")
assert_equal({ "name" => "Ada", "email" => "ada@example.com", "role" => "admin" }, actual)

If you prefer symbols in the test, convert once at the edge rather than sprinkling to_s through the expectation:

actual = user.attributes.symbolize_keys.slice(:name, :email, :role)
assert_equal expected, actual

Slicing has a nice side effect: when a teammate adds a column next month, none of your tests break. A test that asserts on user.attributes in full is a test that fails every time the schema changes, which trains people to ignore failures.

The inverse is except. If the record has two or three volatile columns and everything else matters, exclude the volatile ones instead:

actual = user.attributes.except("id", "created_at", "updated_at")

I use slice by default and except only for a model where nearly every column is part of the contract, such as a serializer test.

attributes versus as_json versus serializable_hash

These three look similar and are not interchangeable.

user.attributes        # string keys, raw Ruby types (Time, BigDecimal, enum string)
user.serializable_hash # string keys, honours :only, :except, :methods, :include
user.as_json           # string keys, JSON-friendly types (timestamps become strings)

The important difference is the value types. attributes hands back what ActiveRecord has typecast: a created_at is an ActiveSupport::TimeWithZone, a decimal column is a BigDecimal. as_json returns what would go over the wire: the same timestamp becomes an ISO 8601 string, and the BigDecimal becomes a string too.

So if you are testing a model, use attributes and expect Ruby types. If you are testing something that renders JSON, compare against JSON.parse(response.body) and expect strings. Mixing them is the second most common source of “these look identical but are not equal” failures.

The types that bite

Even with the keys sorted out, individual values cause trouble.

Timestamps. A Time in your expectation will rarely equal the one the database returns, because the database truncates to microseconds (or milliseconds on some adapters) while Time.current carries nanoseconds:

expected_time = Time.current
record = Event.create!(starts_at: expected_time)

record.reload.starts_at == expected_time # => false on many setups

Either freeze time with travel_to, or compare with a tolerance:

assert_in_delta expected_time.to_f, record.reload.starts_at.to_f, 0.001

Or leave the timestamp out of the hash comparison and assert it separately. I wrote about the general version of this problem in timestamps breaking hash equality.

Decimals. BigDecimal("19.99") == 19.99 is false, because the float is not exactly 19.99. Build your expected hash with BigDecimal("19.99") or 19.99.to_d, never a bare float.

Enums. With enum :role, { member: 0, admin: 1 }, user.attributes["role"] returns the string "admin", not the integer 1 and not a symbol. If your expected hash says role: :admin, it will fail. Use the string.

JSON and serialized columns. A jsonb column returns a hash with string keys, whatever symbols you assigned:

Setting.create!(prefs: { theme: "dark" })
Setting.last.prefs # => { "theme" => "dark" }

This is the same symbol-versus-string trap as everywhere else, and it hides well because you wrote symbols on the way in.

Use assert_equal on the hash, not on each field

It is tempting to write one assertion per field. Do not, unless you want to see only the first failure:

assert_equal "Ada", user.name
assert_equal "ada@example.com", user.email   # never reached if the line above fails

A single hash comparison reports every mismatch in one run, which saves a fix-and-rerun loop per field. Hash comparison gives you the whole picture, provided the diff output is readable, and that is where the default Minitest output lets you down for large hashes. If you run into that, why Minitest hash diffs are hard to read covers it. The minitest-hashdiff gem (https://rubygems.org/gems/minitest-hashdiff) exists for the same reason.

RSpec has a better built-in answer

In RSpec you can skip the slicing and use have_attributes, which compares only the attributes you list and handles typecasting through the reader methods:

expect(user).to have_attributes(name: "Ada", email: "ada@example.com", role: "admin")

It calls user.name, user.email, and user.role, so symbol keys just work and you never touch attributes. For a nested hash, include does the same job:

expect(user.attributes).to include("name" => "Ada", "role" => "admin")

Minitest has no direct equivalent, which is why the slice pattern above is worth making a habit.

A small helper that pays for itself

If you do this in more than a handful of tests, extract it:

# test/test_helper.rb
def assert_attributes(expected, record)
  actual = record.attributes.symbolize_keys.slice(*expected.keys)
  assert_equal expected, actual
end

Now the test reads as intent:

assert_attributes({ name: "Ada", role: "admin" }, user)

Notice that it slices by the expected keys, so the helper never asks the record for anything the test did not mention. It also fails cleanly if you mistype a key, because slice simply returns a hash without it and the comparison shows the gap.

What I actually do

Slice to the fields the code is responsible for, use string values for enums, BigDecimal for money, and keep timestamps out of the hash unless the time is the point of the test. Prefer a single hash assertion over a column of field assertions so you see every mismatch at once. In RSpec reach for have_attributes; in Minitest keep a three-line assert_attributes helper around.

When two hashes look identical but still fail, paste both into Try RubyHash to see exactly which key or type differs, with nothing uploaded.

Enjoyed this post?

Subscribe to get notified when we publish more Ruby and Rails content.