Ruby on rails 如何对验证器进行RSpec?
我已经创建了一个验证器文件,并在该验证器文件中编写了模型的验证,我想对该验证器的每个属性进行Rspec,我该怎么做Ruby on rails 如何对验证器进行RSpec?,ruby-on-rails,ruby-on-rails-5,Ruby On Rails,Ruby On Rails 5,我已经创建了一个验证器文件,并在该验证器文件中编写了模型的验证,我想对该验证器的每个属性进行Rspec,我该怎么做 #This is my validator # my path app/models/validators/book.rb class Validators:: Book include ActiveModel::Validations attr_accessor :title # initialize attributes def initialize(bo
#This is my validator
# my path app/models/validators/book.rb
class Validators:: Book
include ActiveModel::Validations
attr_accessor :title
# initialize attributes
def initialize(book = {})
unless book.class.name == "book"
raise "Argument is not of Book model object."
end
# loop through each user attribute and assign to its relevant attribute of validation class
book.attributes.each do |name, value|
# assign an existing attribute to validator class with the value
if self.respond_to? name
send("#{name}=", value)
end
end
validates_length_of :title, minimum: 2, maximum: 8
end
Thoughbot的gem提供了一些测试验证的好方法:
RSpec.describe Robot, type: :model do
it { should validate_presence_of(:arms) }
end
我解决了我的问题。 谢谢你的帮助
# And path of this file is spec/models/validators/book_spec.rb
require 'rails_helper'
RSpec.describe Validators::Book do
it {should validate_length_of(:title).is_at_most(64), allow_value(nil).for(:user_lastname)}
end
这是我用过的,但它只适用于模型,不适用于验证器。这是一次很好的尝试,你一定会成功的。