Skip to content

Instantly share code, notes, and snippets.

@akampjes
Last active November 24, 2015 03:51
Show Gist options
  • Save akampjes/dc7243a3a84f16128193 to your computer and use it in GitHub Desktop.
Save akampjes/dc7243a3a84f16128193 to your computer and use it in GitHub Desktop.

Context and Describe

We tend to use describe() for things and context() for context

RSpec book

Describe

  • wrap a set of tests 'against one functionality'
  • "use describe for things"
  • start describe with '#' for instance method
  • start describe with '.' for class method

Context

  • wrap a set of tests against one functionality 'under the same state'
  • "use context for state"
  • start context with when/with

Example

describe '#dead' do
  subject(:cat) { Cat.new(lives: starting_lives) }
  
  context "with nine lives" do
    let(:starting_lives) { 9 }
    
    it { is_expected.not_to be_dead }
  end
  
  context "with no lives" do
    let(:starting_lives) { 0 }
    
    it { is_expected.to be_dead }
  end
  
  # Alternatively, sometimes you can't use is_expected syntax
  context 'when cat has no more lives' do
    let(:starting_lives) { 0 }

    it 'is dead :(' do
      expect(cat).to be_dead
    end
  end
end

Bonus

  • don't use should in test names
    • instead say what will happen
  • prefer active verbs
  • Use it to say what you're expecting to happen

http://lmws.net/describe-vs-context-in-rspec

http://jakegoulding.com/presentations/rspec-structure

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment