Search code examples
ruby-on-railsrubyruby-on-rails-4rspecrspec-rails

rspec-given error `Then` is not available from within an example (e.g. an `it` block)


I'm using rspec-given and keep receiving this error.

Failure/Error: Then { Then is not available from within an example (e.g. an it block) or from constructs that run in the scope of an example (e.g. before, let, etc). It is only available on an example group (e.g. a describe or context block).

describe SchoolService do
  Given(:school) { create(:school_with_applications) }
  Given(:service) { School.new(@school) }

  describe 'create_default_programs_and_year_grades!' do
    it 'checks program size' do 
      When { service.create_default_programs_and_year_grades! }
      Then { expect(school.programs.size).to eq 3 }
    end
  end
end

Solution

  • The error message says it all:

    Then is not available from within an example (e.g. an it block) or from constructs that run in the scope of an example (e.g. before, let, etc). It is only available on an example group (e.g. a describe or context block).
    

    please read the error message carefully. And you have the solution in the error message itself.

    You can't use Then inside a it block, you can only use Then either with describe or context block.

    So, to solve your problem, just use context instead of it:

    describe SchoolService do
      Given(:school) { create(:school_with_applications) }
      Given(:service) { School.new(@school) }
    
      describe 'create_default_programs_and_year_grades!' do
        context 'checks program size' do 
          When { service.create_default_programs_and_year_grades! }
          Then { expect(school.programs.size).to eq 3 }
        end
      end
    end
    

    See more examples here.