Ruby on rails Rails模型方法无法正常工作

Ruby on rails Rails模型方法无法正常工作,ruby-on-rails,factory-bot,Ruby On Rails,Factory Bot,我尝试在我的模型中测试一些方法,但是它们工作得不好,当它应该返回false时,它似乎没有返回false-有什么建议吗 class Registration < ActiveRecord::Base validate :check_duplicate_section def check_duplicate_section all_registrations = Registration.all all_registrations.each do |reg| p

我尝试在我的模型中测试一些方法,但是它们工作得不好,当它应该返回false时,它似乎没有返回false-有什么建议吗

class Registration < ActiveRecord::Base
validate :check_duplicate_section
def check_duplicate_section
    all_registrations = Registration.all
    all_registrations.each do |reg|
        puts reg.section_id
        if reg.section_id == self.section_id && reg.student_id == self.student_id 
        errors.add(:registration, "Already exists")
        return false
        end
    return true
end
end
类注册
测试文件:(@bruce已在前面定义)

类注册测试“mike”)
good_reg=FactoryGirl.build(:registration,:section=>@section2,:student=>@mike)
bad_reg=FactoryGirl.build(:registration,:section=>@section1,:student=>@bruce)
bad_reg2=FactoryGirl.build(:registration,:section=>@section2,:student=>@mike)
断言等于真、好、有效吗?
assert_equal false,bad_reg.valid?
assert_equal false,bad_reg2.valid?

从您试图使用的
检查重复部分的外观来看,最好使用内置的
唯一性
验证

validates :section_id, uniqueness: { scope: :user_id }
如果不想使用此方法,请将方法更改为

def check_duplicate_section
  if Registration.where(section_id: self.section_id, student_id: self.student_id).exists?
    errors.add :registration, "Already exists"
  end
end
此外,在测试中,您使用的是
build
,它不会将任何内容保存到数据库中。您应该使用
create
,或者更好的方法是使用mock强制db查询的返回值


使用内置验证方法的好处是,您不需要测试它,因为它应该可以工作。

从您试图使用的
检查重复部分看,最好使用内置的
唯一性
验证

validates :section_id, uniqueness: { scope: :user_id }
如果不想使用此方法,请将方法更改为

def check_duplicate_section
  if Registration.where(section_id: self.section_id, student_id: self.student_id).exists?
    errors.add :registration, "Already exists"
  end
end
此外,在测试中,您使用的是
build
,它不会将任何内容保存到数据库中。您应该使用
create
,或者更好的方法是使用mock强制db查询的返回值

使用内置验证方法的好处是您不需要测试它,因为它应该可以工作