我正在尝试在不加载整个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
答案 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