describe and context in RSpec

Firstly, be clear about we describe method as below convention (. or :: referring to a class method's name and # referring to an instance method's name).
describe and context group related tests together, and they are alias_method methods. The diffenece of them is their usage scenario:

  • Use describe for things
  • Use context for states
things
bad:  context "#matriculate"
better:   describe "#matriculatet"

states
bad: describe "when the student is sick"
better: context "when the student is sick"

In generally, context is at the top-level in rspec file, and rspec encourages developer to organize tests by things
Tip: when use it to describe something ,if it's too long, we should use context instead
for example:

BAD:

  it 'has 422 status code if an unexpected params will be added' do

BETTER:
  context 'when not valid' do
  it {should respond_with 422  }
  end

describe more suitable for complex return values, and context for state. Mostly, tests deal with a list of state, so a list of context put in the describe is more reasonable.
Oftenly, describe name should match the method name, but context should not do that. best way to name context is to explain why the method would be call.
Finally, we analyse sample code fragment as below:

describe Clearance::Configuration do
  ...
  describe "allow_sign_up?" do
    context "when allow_sign_up is configured to false" do
      Clearance.configure { |config| config.allow_sign_up = false  }
      expect(Clearance.configuration.allow_sign_up?).to qe true
    end

    context "when allow_sign_up has not been configured" do
      it "return true" do
        expect(Clearance.configuration.allow_sign_up?).to eq true
      end
    end
  end

the code frome Clearance,a Rails authentication gem with email & password.In the Configuration class test, allow_sign_up? is a class method, which return value type is boolean.
describe Clearance::Configuration block in the top-level, group the whole configuration_spec.rb. allow_sign_up is a thing, so it's better to use describe. Move in deapth, two states nested in the describe "allow_sign_up?" block. It is worth explaining that allow_sign_up? is method name, Naming describe as method name,when allow_sign_up is configured to false, explaining which situation would call the method, meet the conventions mentioned above.
I strongly recommand you to read:

  • betterspecs
  • rspec-structure

你可能感兴趣的:(describe and context in RSpec)