Search code examples
rubyunit-testingrspec

Testing modules in RSpec


What are the best practices on testing modules in RSpec? I have some modules that get included in few models and for now I simply have duplicate tests for each model (with few differences). Is there a way to DRY it up?


Solution

  • I found a better solution in rspec homepage. Apparently it supports shared example groups. From https://www.relishapp.com/rspec/rspec-core/v/2-13/docs/example-groups/shared-examples!

    Shared Example Groups

    You can create shared example groups and include those groups into other groups.

    Suppose you have some behavior that applies to all editions of your product, both large and small.

    First, factor out the “shared” behavior:

    shared_examples_for "all editions" do   
      it "should behave like all editions" do   
      end 
    end
    

    then when you need define the behavior for the Large and Small editions, reference the shared behavior using the it_should_behave_like() method.

    describe "SmallEdition" do  
      it_should_behave_like "all editions"
      it "should also behave like a small edition" do   
      end 
    end