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
Written by Gilbert
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#