快速测试:如何在测试中仅加载部分active_model

时间:2013-01-28 21:15:57

标签: ruby-on-rails rspec

我正在尝试在不加载整个Rails应用程序的情况下测试模型。我想只包含与我正在测试的类相关的rails部分。如何正确地要求active_model / validations?我以为我已经正确完成了,但是下面的设置会引发这个错误:

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

正在测试的模型:

#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/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

2 个答案:

答案 0 :(得分:1)

您的测试无效,因为Project(在您的测试中)未从ActiveRecord::Base继承,因此它没有validate方法。要求ActiveModel验证只是使ActiveModel模块可用,您需要在类中实际包含它以使其方法可用,如下所示:

class Project
  include ActiveModel::Validations
end

更多关于在this article中单独使用ActiveModel。

更多参考:

答案 1 :(得分:0)

根据Shioyama的帖子,我最终不得不要求我需要的东西。这就是它的样子。

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