Advertisement
nafaabout

Correction for RSpec – you should avoid let and before block

Feb 6th, 2018
307
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.42 KB | None | 0 0
  1. require 'spec_helper'
  2.  
  3. module Users
  4.   describe NameService do
  5.     describe '#name' do
  6.       let(:user) { User.new }
  7.       # I don't like using subject {}, so I name the subject following the
  8.       # described class name, so when you read the example bellow, you know
  9.       # directly what kind is that object. I hate also using the described_class helper
  10.       # it makes changing the specs easier later on when the class changes (which it doesn't
  11.       # happen very frequentely), so you only change it in one place. But it makes
  12.       # reading examples very hard, and you need to go back and forth between
  13.       # the example and the `describe Class`.    
  14.       let(:name_service){ NameService.new(user) }
  15.  
  16.       # this is shared between all the specs, for DRYing code.
  17.       before do
  18.        allow(user).to receive(:posts?).and_return(has_posts)
  19.       end
  20.      
  21.       # use context instead of "if statements"
  22.       context 'WHEN user does NOT HAVE posts' do
  23.         # this makes it clear what this context block is all about
  24.         let(:has_posts) { false }
  25.  
  26.         it 'returns user.name' do
  27.           expect(name_service.name).to eq(user.name)
  28.         end
  29.       end
  30.  
  31.       context 'WHEN user HAS posts' do
  32.         let(:has_posts) { true }
  33.  
  34.         it 'returns "#{user.name} (has posts)"' do
  35.           expect(name_service.name).to eq("#{user.name} (has posts)")
  36.         end
  37.       end
  38.     end
  39.   end
  40. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement