diff --git a/README.md b/README.md index e42fab1..7572e3c 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/). For a steady stream of TILs from a variety of rocketeers, checkout [til.hashrocket.com](https://til.hashrocket.com/). -_813 TILs and counting..._ +_814 TILs and counting..._ --- @@ -608,6 +608,7 @@ _813 TILs and counting..._ - [A Shorthand For Rerunning Failed Tests With RSpec](ruby/a-shorthand-for-rerunning-failed-tests-with-rspec.md) - [Are They All True?](ruby/are-they-all-true.md) +- [Assert About An Object's Attributes With RSpec](ruby/assert-about-an-objects-attributes-with-rspec.md) - [Assoc For Hashes](ruby/assoc-for-hashes.md) - [Block Comments](ruby/block-comments.md) - [Chaining Multiple RSpec Change Matchers](ruby/chaining-multiple-rspec-change-matchers.md) diff --git a/ruby/assert-about-an-objects-attributes-with-rspec.md b/ruby/assert-about-an-objects-attributes-with-rspec.md new file mode 100644 index 0000000..94047df --- /dev/null +++ b/ruby/assert-about-an-objects-attributes-with-rspec.md @@ -0,0 +1,31 @@ +# Assert About An Object's Attributes With RSpec + +When testing an object that gets created as the result of some process, it can +be useful to assert about the attributes of that object. Not all of the +attributes are relevant and some can be hard to reliably test. Rather than +asserting about the result of calling `#attributes` or `#to_h` on an object, we +can focus in with the [`have_attributes` +matcher](https://relishapp.com/rspec/rspec-expectations/docs/built-in-matchers/have-attributes-matcher) +provided by RSpec. + +```ruby +RSpec.describe "have_attributes" do + it "can assert on an ActiveRecord object" do + book = Book.create(title: "Fledling", isbn: "123") + + expect(book).to have_attributes(title: "Fledgling", isbn: "123") + end + + it "can assert on a Struct" do + Name = Struct.new(:first, :last) + some_name = Name.new("Liz", "Lemon") + + expect(some_name).to have_attributes(first: "Liz") + end +end +``` + +In this example we were able to assert about all or just a subset of the +attributes on both an `ActiveRecord` object and a `Struct`. + +See [the docs](https://relishapp.com/rspec/rspec-expectations/docs/built-in-matchers/have-attributes-matcher) for more details.