Rails模型方法不能很好地工作

时间:2013-03-04 01:51:46

标签: ruby-on-rails factory-bot

我有一些方法,我试图在我的模型中测试,但它们运行不正常,它似乎没有返回错误,它应该 - 任何建议?

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)

class RegistrationTest < ActiveSupport::TestCase

should "not allow invalid student registrations" do
    @mike = FactoryGirl.create(:student, :first_name => "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 true, good_reg.valid?
    assert_equal false, bad_reg.valid?
    assert_equal false, bad_reg2.valid?

1 个答案:

答案 0 :(得分:1)

根据您使用check_duplicate_section尝试的内容,最好使用内置的uniqueness验证

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或更好,使用模拟来强制返回db查询的值。

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