We make extensive use of ViewComponents in our Rails app. If you haven’t come across this new addition to the Rails toolkit, it takes some ideas from React and brings them to the rails party. It’s worth checking out. It has allowed us to rapidly build new interfaces and try out new ideas as we expand our product.
We already use rspec-snapshot gem elsewhere in our application to test generated reports, so it was just a matter of comparing HTML instead of CSV files! Here’s a quick tip on how we do it.
In the helper below, we use the after hook only target component type tests where snapshotting is enabled. We then use the metadata from the test case to compose the filename.
If we detect that nothing has been assigned to rendered_component, we raise an error so the test fails. Otherwise, we use rspec-snapshot’s matcher match_snapshot to test everything was as expected.
Our test then looks like this:
On the first run, this ends up creating a file structure and snapshots to compare against in the future:
Now if we want to update our snapshots we can just run the following command.
Otherwise, it works just as the rest of our RSpec testing does. No doubt in the future someone will wrap this all up in a nice gem, but until then this quick solution is working well. Hope this is interesting to anyone out there exploring view components! If you end up using this technique in your teams, let us know on Twitter @trybearer!