Skip to content

Commit 179f5ff

Browse files
committed
Add Assert About An Object's Attributes With RSpec as a ruby til
1 parent e43c059 commit 179f5ff

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
1010
For a steady stream of TILs from a variety of rocketeers, checkout
1111
[til.hashrocket.com](https://til.hashrocket.com/).
1212

13-
_813 TILs and counting..._
13+
_814 TILs and counting..._
1414

1515
---
1616

@@ -608,6 +608,7 @@ _813 TILs and counting..._
608608

609609
- [A Shorthand For Rerunning Failed Tests With RSpec](ruby/a-shorthand-for-rerunning-failed-tests-with-rspec.md)
610610
- [Are They All True?](ruby/are-they-all-true.md)
611+
- [Assert About An Object's Attributes With RSpec](ruby/assert-about-an-objects-attributes-with-rspec.md)
611612
- [Assoc For Hashes](ruby/assoc-for-hashes.md)
612613
- [Block Comments](ruby/block-comments.md)
613614
- [Chaining Multiple RSpec Change Matchers](ruby/chaining-multiple-rspec-change-matchers.md)
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Assert About An Object's Attributes With RSpec
2+
3+
When testing an object that gets created as the result of some process, it can
4+
be useful to assert about the attributes of that object. Not all of the
5+
attributes are relevant and some can be hard to reliably test. Rather than
6+
asserting about the result of calling `#attributes` or `#to_h` on an object, we
7+
can focus in with the [`have_attributes`
8+
matcher](https://relishapp.com/rspec/rspec-expectations/docs/built-in-matchers/have-attributes-matcher)
9+
provided by RSpec.
10+
11+
```ruby
12+
RSpec.describe "have_attributes" do
13+
it "can assert on an ActiveRecord object" do
14+
book = Book.create(title: "Fledling", isbn: "123")
15+
16+
expect(book).to have_attributes(title: "Fledgling", isbn: "123")
17+
end
18+
19+
it "can assert on a Struct" do
20+
Name = Struct.new(:first, :last)
21+
some_name = Name.new("Liz", "Lemon")
22+
23+
expect(some_name).to have_attributes(first: "Liz")
24+
end
25+
end
26+
```
27+
28+
In this example we were able to assert about all or just a subset of the
29+
attributes on both an `ActiveRecord` object and a `Struct`.
30+
31+
See [the docs](https://relishapp.com/rspec/rspec-expectations/docs/built-in-matchers/have-attributes-matcher) for more details.

0 commit comments

Comments
 (0)