我正在研究我公司编写的软件的测试框架。我们的产品是基于Web的,在运行RESTful请求后,我想处理结果。我希望能够在每个命令类中具有activerecord类型验证,以便在运行之后,结果将自动针对所有“验证”进行测试。但是,我不知道该怎么做。我的代码看起来像这样(简化以显示重要部分)。
class CodesecureCommand
def execute
result = RestClient.post("http://#{codesecure.host_name_port}#{path}", post_data)
return parse(result) #parse simple returns a Hpricot document
end
end
class RunScan < CodesecureCommand
#What I have now
#I have to override the execute function so that it calls the local success method
#to see if it failed or not.
def execute()
result = super()
if success(result)
return true
else
end
end
def success(result)
result.search('div.transaction-message') do |message|
if message.innerHTML.scan(/Configure abuse setting for domain users successfully\./).length == 1
return true
end
end
end
#What I would like is to be able to call execute (without having to override it).
#then after it runs it calls back to this class to check
#if the regex matches the command was successful and returns true
test_success /regex/
#if test_success fails then these are called
#the idea being that I can use the regex to identify errors that happened then
#report them to the user
identify_error /regex/, "message"
identify_error /regex/, "message"
end
end
我想要的是,在调用execute方法之后,test_success和identify_error会像activerecord中的验证一样被自动调用。谁能告诉我怎么做?感谢
答案 0 :(得分:3)
如果不仔细看你的代码,这是我对实现验证类方法的看法:
module Validations
def self.included(base)
base.extend ClassMethods
end
def validate
errors.clear
self.class.validations.each {|validation| validation.call(self) }
end
def valid?
validate
errors.blank?
end
def errors
@errors ||= {}
end
module ClassMethods
def validations
@validations ||= []
end
def validates_presence_of(*attributes)
validates_attributes(*attributes) do |instance, attribute, value, options|
instance.errors[attribute] = "cant't be blank" if value.blank?
end
end
def validates_format_of(*attributes)
validates_attributes(*attributes) do |instance, attribute, value, options|
instance.errors[attribute] = "is invalid" unless value =~ options[:with]
end
end
def validates_attributes(*attributes, &proc)
options = attributes.extract_options!
validations << Proc.new { |instance|
attributes.each {|attribute|
proc.call(instance, attribute, instance.__send__(attribute), options)
}
}
end
end
end
它假设ActiveSupport在Rails环境中。您可能希望将其扩展为允许每个属性使用instance.errors[attribute] << "the message"
多个错误,但我遗漏了这样的晦涩难懂,以便尽可能简化这个简短的样本。
这是一个简短的用法示例:
class MyClass
include Validations
attr_accessor :foo
validates_presence_of :foo
validates_format_of :foo, :with => /^[a-z]+$/
end
a = MyClass.new
puts a.valid?
# => false
a.foo = "letters"
puts a.valid?
# => true
a.foo = "Oh crap$(!)*#"
puts a.valid?
# => false
答案 1 :(得分:2)
您想要Validatable:sudo gem install validatable
class Person
include Validatable
validates_presence_of :name
attr_accessor :name
end
此外,Validatable不依赖于ActiveSupport。