ruby.social is one of the many independent Mastodon servers you can use to participate in the fediverse.
If you are interested in the Ruby programming language, come join us! Tell us about yourself when signing up. If you just want to join Mastodon, another server will be a better place for you.

Administered by:

Server stats:

1.1K
active users

Henrik Nyh

Came up with a useful pattern – combining `uniq` and `sole` to get a value if unique, and raise otherwise.

```
DEV (main)> [ 1, 1, 1 ].uniq.sole
1
DEV (main)> [ 1, 1, 2 ].uniq.sole
(irb):135:in `<main>': multiple items found (Enumerable::SoleItemExpectedError)
```

Using it in a spec to get a single class from multiple records assumed to have the same class:

```
transaction_class = [ transaction_1, transaction_2 ].map(&:class).uniq.sole
expect(transaction_class.some_scope).to …
```

@henrik also, crashing in tests is so underrated. I've often seen checks like this expressed as

assert_equal 1, [1,1,1].uniq.lenght

Most often something like

assert_equal 1, results.length
assert_equal "foo", results.first

@mark Yeah, crashing is great. You can often get clearer info sooner. Using `Item.last!` instead of `Item.last` and so on (getting an exception instead of nil) is one I use a lot. There’s rarely good reason not to use that one if you expect a value (in tests or otherwise).