← Back to Upcase

Best way to test a gemified shared example


(Geoff Harcourt) #1

After duplicating some shared example code that I think would be useful to others, I want to package it up as a gem. However, I’m having a little trouble figuring out how to test the shared example.

What I’m trying to do is define a class in the spec like this:

describe MyGemsName do
  describe "shared examples" do
    describe "shared example: 'a common thing'" do
      it "runs the common thing tests against the model" do
        class MyClass
        end

        describe MyClass do
           it_behaves_like "a common thing"
        end
      end
    end
  end
end

This throws an exception, as within an it-do-end block is not a valid place to start putting new describe blocks. I searched the goog and came up empty, as it’s sort of confusing to type “test shared example” and not to get a bunch of code about how to do a shared example as opposed to how to test that one is working properly.

I know this code works because I swapped it in place of my non-Gemified code from before and the tests execute properly. However, I don’t want to ship a gem without test coverage. (I realize this is a little backward on TDD, but the code spike was unbelievably simple.) Does anyone know how I can effectively test 1) that the shared example code can be called correctly and 2) that the shared example is doing what I expected it to do?

Thanks,
Geoff


(Chad Pytel) #2

Trying nesting it a bit differently, like this:

describe MyGemsName do
  describe "shared examples" do
    describe "shared example: 'a common thing'" do
      class MyClass
      end
      describe MyClass do
       it_behaves_like "a common thing"
      end
    end
  end
end

If that doesn’t work, then you can move it out of the describe entirely.

class MyClass
end

describe MyGemsName do
  describe "shared examples" do
    describe "shared example: 'a common thing'" do
      describe MyClass do
       it_behaves_like "a common thing"
      end
    end
  end
end

(Chad Pytel) #3

You could also move MyClass into a separate file, included in spec_helper.rb


(Geoff Harcourt) #4

Hey @cpytel, thanks for the feedback!

I think I asked my question poorly. I’m trying to verify that the tests in the shared examples get executed successfully. After reorganizing the code there I do avoid the undefined method error, so that’s a huge move forward. At this point, is the best strategy to use have_received to check if the tests got run?