Module testing module, which is included in the ActiveRecord model

I have a module like this (but more complicated):

module Aliasable def self.included(base) base.has_many :aliases, :as => :aliasable end end 

which I include in several models. Currently, for testing, I am creating another module, as shown below, which I just include in the test case

 module AliasableTest def self.included(base) base.class_exec do should have_many(:aliases) end end end 

The question is, how can I test this module separately? Or is it good enough. There seems to be probably the best way to do this.

+4
source share
1 answer

First, self.included not a good way to describe your modules, and class_exec unnecessarily complicates the situation. Instead, you should extend ActiveSupport::Concern , as in:

 module Phoneable extend ActiveSupport::Concern included do has_one :phone_number validates_uniqueness_of :phone_number end end 

You did not specify which test framework you are using, but RSpec covers exactly this case. Try the following:

 shared_examples_for "a Phoneable" do it "should have a phone number" do subject.should respond_to :phone_number end end 

Assuming your models look like this:

 class Person class Business include Phoneable include Phoneable end end 

Then in your tests you can:

 describe Person do it_behaves_like "a Phoneable" # reuse Phoneable tests it "should have a full name" do subject.full_name.should == "Bob Smith" end end describe Business do it_behaves_like "a Phoneable" # reuse Phoneable tests it "should have a ten-digit tax ID" do subject.tax_id.should == "123-456-7890" end end 
+8
source

All Articles