Rails & RSpec - Testing Concerns class methods Rails & RSpec - Testing Concerns class methods ruby-on-rails ruby-on-rails

Rails & RSpec - Testing Concerns class methods


Check out RSpec shared examples.

This way you can write the following:

# spec/support/has_terms_tests.rbshared_examples "has terms" do   # Your tests hereend# spec/wherever/has_terms_spec.rbmodule TestTemps  class HasTermsDouble    include ActiveModel::Validations    include HasTerms  endenddescribe HasTerms do  context "when included in a class" do    subject(:with_terms) { TestTemps::HasTermsDouble.new }    it_behaves_like "has terms"  endend# spec/model/contract_spec.rbdescribe Contract do  it_behaves_like "has terms"end


You could just test the module implicitly by leaving your tests in the classes that include this module. Alternatively, you can include other requisite modules in your dummy class. For instance, the validates methods in AR models are provided by ActiveModel::Validations. So, for your tests:

class DummyClass  include ActiveModel::Validations  include HasTermsend

There may be other modules you need to bring in based on dependencies you implicitly rely on in your HasTerms module.


I was struggling with this myself and conjured up the following solution, which is much like rossta's idea but uses an anonymous class instead:

it 'validates terms' do  dummy_class = Class.new do    include ActiveModel::Validations    include HasTerms    attr_accessor :agrees_to_terms    def self.model_name      ActiveModel::Name.new(self, nil, "dummy")    end  end  dummy = dummy_class.new  dummy.should_not be_validend