Last Updated: February 25, 2016
·
1.343K
· mindeavor

Rails TDD: Stub a model class method before require

Let's say you have the following:

# app/models/user.rb
class User < ActiveRecord::Base
  authenticates_with_sorcery!
end

If you want to test this model without loading the rails environment, and don't need to test authenticates_with_sorcery!, you can use the following:

def stub_ar_class_method(class_name, method_name)
  begin
    klass = Module.const_get(class_name)
  rescue NameError
    klass = Class.new(ActiveRecord::Base)
    Object.const_set class_name, klass
  end

  unless klass.methods.include?(method_name)
    klass.send :define_singleton_method, method_name, lambda {|*|}
  end
end

Then, in your specs, you can stub methods before requiring the class:

# user_spec.rb
stub_ar_class_method :User, authenticates_with_sorcery!
require '/path/to/app/models/user.rb'

# Begin test suites...

Why is this useful? Mainly because it keeps your core tests fast:

  • You don't have to load the rails environment
  • You don't have to load any other unnecessary libraries
  • You can easily stub class methods inside a helper method body