| name | rspec |
| description | MUST use this skill when writing, reviewing, or modifying Ruby RSpec tests (*_spec.rb) in Canvas |
When writing or reviewing RSpec tests in Canvas, there are several guidelines to ensure tests are effective and maintainable.
Canvas' codebase is quite old, so there are many legacy tests that don't follow modern best practices.
- Prefer
let and let! for defining test data instead of instance variables. This provides better scoping and lazy loading of test data. This also applies to using let instead of before blocks for setting up test data.
- When an ActiveRecord model instance is shared across multiple tests without any stubbed methods, use
let_once to define it. This will create the object once and reuse it across examples, improving test performance.
- When using
subject, remember that it's a noun -- don't use it as a way to perform a common action across multiple examples. The subject should be the object under test. If you want to perform a common action across multiple examples, write a method. You can call that in each action. Or use a before block if it makes sense.
- Look for repetitive patterns in your tests, and extract them into
let, before blocks, helper methods, or shared context as appropriate. This will make your tests more DRY and easier to read.
- Don't create "factory" methods for models unless the method is doing something non-trivial. Most factory methods are simply guessing a couple of defaults (that you're likely passing in anyway) and then calling
create! on the model. Simply pass your attributes directly to create! yourself. If you find yourself wanting to infer the same values over and over, consider a before_validation hook on the model that can infer them for you.
- Don't use raw unless absolutely necessary. and provide better guarantees that your test doubles are accurate representations of the real objects.