How to mix a module into an rspec context

后端 未结 2 644
遇见更好的自我
遇见更好的自我 2021-02-02 17:49

How can I mix a module into an rspec context (aka describe), such that the module\'s constants are available to the spec?

module Foo
  FOO = 1
end

         


        
相关标签:
2条回答
  • 2021-02-02 18:21

    You can use RSpec's shared_context:

    shared_context 'constants' do
      FOO = 1
    end
    
    describe Model do
      include_context 'constants'
    
      p FOO    # => 1
    end
    
    0 讨论(0)
  • 2021-02-02 18:47

    You want extend, not include. This works in Ruby 1.9.3, for instance:

    module Foo
      X = 123
    end
    
    describe "specs with modules extended" do
      extend Foo
      p X # => 123
    end
    

    Alternatively, if you want to reuse an RSpec context across different tests, use shared_context:

    shared_context "with an apple" do
      let(:apple) { Apple.new }
    end
    
    describe FruitBasket do
      include_context "with an apple"
    
      it "should be able to hold apples" do
        expect { subject.add apple }.to change(subject, :size).by(1)
      end
    end
    

    If you want to reuse specs across different contexts, use shared_examples and it_behaves_like:

    shared_examples "a collection" do
      let(:collection) { described_class.new([7, 2, 4]) }
    
      context "initialized with 3 items" do
        it "says it has three items" do
          collection.size.should eq(3)
        end
      end
    end
    
    describe Array do
      it_behaves_like "a collection"
    end
    
    describe Set do
      it_behaves_like "a collection"
    end
    
    0 讨论(0)
提交回复
热议问题