Last active
December 13, 2015 21:39
-
-
Save phosphene/4979019 to your computer and use it in GitHub Desktop.
Sane guidelines for setting up Rspec tests with subject, let, and before(:each)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1. subject: | |
Use subject for creating the subject. Named subjects should be preferred unless | |
used only implicitly thereafter | |
i.e.: | |
subject(:user) { create(:user) } | |
where "user.bar" will be preferred over "subject.bar" | |
2. let: | |
Use let and let! for non-subject vars or objects needed. | |
let is lazy, memoized, and local. Three wins | |
3. before: | |
Use before(:each) for methods or complex setups that require methods. | |
Or only use before when subject and let are not enough. | |
Beware of before(:all): avoid it unless you know why and where. | |
4. Consider writing your own helper methods for very complex setup. | |
However, if setup is complex, this can be an indication that design of | |
classes to be tested is too complicated and should be simplified. | |
Examples: | |
Here is an example complex set up from VCR specs that uses subject, let, and before: | |
subject { HooksClass.new } | |
let(:invocations) { [] } | |
before(:each) do | |
subject.instance_eval do | |
define_hook :before_foo | |
define_hook :before_bar | |
end | |
end | |
Here is an example that creates test doubles (mocks) in a context using let: | |
describe Transfer do | |
context "transfer with amount of 10" do | |
let(:source_account) { double :source_account, :decrease => nil } | |
let(:destination_account) { double :destination_account, :increase => nil } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment