我有2个模型共享一个简单的belongs_to / has_many关系:房间属于Building
我创建了一个名为total_number_rooms_limited_to_15的自定义验证器,确保我无法为给定的建筑物创建超过15个房间。
class Room < ActiveRecord::Base
# -- Relationships --------------------------------------------------------
belongs_to :admin_user, :foreign_key => 'admin_user_id'
belongs_to :building, :foreign_key => 'building_id'
# -- Validations ----------------------------------------------------------
validates :room_filename,
presence: true
# associated models primary key validates
validates :admin_user_id,
presence: true
validates :building_id,
presence: true
validate :total_number_rooms_limited_to_15
private
def total_number_rooms_limited_to_15
errors[:base] << "There can't be more than 15 rooms. There are already 15 .
<br/>Please remove another one or drop trying adding this one.".html_safe
unless ( self.building.rooms.count < 15 )
end
但问题是,在创建了这个新的验证器后,我所有的常规&#34;基本测试失败。
require 'spec_helper'
RSpec.describe Room, type: :model do
before(:each) do
@attr = {
room_filename: "xyz"
}
end
# -- Models Tests --------------------------------------------------------
describe "tests on ST's models validations for room_filename" do
it { is_expected.to validate_presence_of(:room_filename) }
it { is_expected.not_to allow_value(" ").for(:room_filename) }
end
所有人都给我以下错误消息:
1) Room tests on ST's models validations for room_filename should validate that :room_filename cannot be empty/falsy
Failure/Error:
errors[:base] << "There can't be more than 15 rooms. There are already 15 .
<br/>Please remove another one or drop trying adding this one.".html_safe unless ( self.building.rooms.count < 15 )
NoMethodError:
undefined method `rooms' for nil:NilClass
我尝试在@attr里面添加一个关联的&#34;虚拟&#34;建设,但它没有成功;,得到相同的错误信息:
before(:each) do
@attr = {
room_filename: "xyz",
building_id: 1
}
添加信息
config.before(:suite) do
DatabaseCleaner.clean_with(:truncation, :except => %w(roles))
end
config.before(:each) do
DatabaseCleaner.strategy = :transaction
end
config.before(:each, js: true) do
DatabaseCleaner.strategy = :truncation
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
答案 0 :(得分:0)
对于自定义验证,您需要在测试中实例化新的msj = [int(i) for i in msg if i.isdigit()]
对象。如果您没有Room
或factory_girl
来为测试创建对象,则可以执行以下操作:
fabrication
然后确保您在实例上调用验证而不是before(:each) do
@admin_user = AdminUser.create!(...attributes)
@building = Building.create!(...attributes)
@room = Room.create!(building_id: @building.id, admin_user_id: @admin_user.id)
end
类:
Room