Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test that I've interfaced with a mixin correctly?

Tags:

ruby

mixins

rspec

How do I test that I've interfaced with a mixin correctly?

I have a mixin that provides a class method used similarly to named_scope or protected_attribute. I have tested the mixin extensively and now need to test that the model it's mixed into is using it correctly. I don't want to test the entire mixin again, just that I've called it with the correct args.

the model:

class SomeClass
  include MatchMixin
  match :name
end

the test:

describe SomeClass do
  it { should be_kind_of(MatchMixin) }

  it "calls match with :name" do
    SomeClass.stubs(:match)
    SomeClass.new
    SomeClass.should have_received(:match).with(:name)  # <= this fails
  end
end

the mixin:

module MatchMixin
  extend ActiveSupport::Concern

  module ClassMethods
    def match(arg)
      # lots of awesome code
    end
  end
end

I've tried everything I can think of. Any suggestions?

like image 754
Jon Avatar asked Dec 05 '25 10:12

Jon


1 Answers

I'd personally just use your first example:

it "includes MatchMixin" do
  SomeClass.new.should be_a_kind_of(MatchMixin)
end

However, if your mixin requires some missing pieces to be filled in (i.e. requires some method definitions that it doesn't know how to implement), then you could use RSpec's shared examples.

That then means the spec code itself is written only once, but is exercised with differing inputs.

it_behaves_like "a MatchMixin"
like image 132
d11wtq Avatar answered Dec 09 '25 21:12

d11wtq