Ben Downey
Ben Downey

Reputation: 2665

Fast Testing: How to load only part of active_model in tests

I'm trying to get test a model without loading my entire Rails app. I want to inlcude only the parts of rails relevant to the class I'm testing. How do I require active_model/validations correctly? I thought I had done it correctly, but the setup below throws this error:

undefined method `validate' for Project::Media:Class (NoMethodError)

Model being tested:

#app/models/project/media.rb

class Project::Media < Project  #Project inherits from ActiveRecord::Base

  validate :allowable_media_source

  before_save : classify_link

  #next, all the methods

end

Spec:

#spec/models/project/media_spec.rb

class ActiveRecord
  class Base; end
end

class Project; end

require_relative '../../../app/models/project/media.rb'
require 'active_model/validations'

describe Project::Media do
  #then tests 
end

Upvotes: 1

Views: 78

Answers (2)

Ben Downey
Ben Downey

Reputation: 2665

I ended up having to require what I needed, per Shioyama's post. This is what it looked like.

require 'active_model'
require 'active_model/validations'
require 'active_record/callbacks'
class Project
  include ActiveModel::Validations    
  include ActiveRecord::Callbacks
end

require_relative '../../../app/models/project/media.rb'

#then tests

Upvotes: 0

Chris Salzberg
Chris Salzberg

Reputation: 27374

Your test is not working because Project (in your test) is not inheriting from ActiveRecord::Base, so it has no validate method. Requiring ActiveModel validations just makes the ActiveModel module available, you need to actually include it in your class to make its methods usable, like this:

class Project
  include ActiveModel::Validations
end

More on using ActiveModel in isolation in this article.

More refs:

Upvotes: 1

Related Questions