Rspec - 预期 ActiveRecord::RecordInvalid 但没有提出任何建议?

Rspec - expected ActiveRecord::RecordInvalid but nothing was raised?

我正在使用 rspec 创建测试并尝试引发错误 "ActiveRecord::RecordInvalid",但我一直收到 "expected ActiveRecord::RecordInvalid but nothing was raised"

我是 rspec 测试的新手,这实际上是我第一次直接询问有关堆栈溢出的问题。所以我的问题可能很幼稚,所以我提前道歉。

class InsiderMailAddress < ActiveRecord::Base

   def self.get_list_by_role(role)
   address = InsiderMailAddress.find_by_role(role)
   end
end


 describe "get list by role" do    
   it "raises error when invalid role is given" do
     expect {
     InsiderMailAddress.get_list_by_role(:role)
   }.to raise_error(ActiveRecord::RecordInvalid)
   end
 end

那是错误的异常。

ActiveRecord::RecordInvalid 当记录无效时引发。不言自明。

class Country < ApplicationRecord
  validates_presence_of :name
end

irb(main):001:0> Country.create
   (0.7ms)  BEGIN
   (0.2ms)  ROLLBACK
=> #<Country id: nil, name: nil, created_at: nil, updated_at: nil>
irb(main):002:0> Country.create!
   (0.3ms)  BEGIN
   (0.4ms)  ROLLBACK
ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
    from (irb):2

如您所见,当您调用 .create - but it is when you call the "bang" methods .save! and .create! 时它不会被引发。

您可能正在寻找的是 ActiveRecord::RecordNotFound

irb(main):001:0> Country.find(1)
  Country Load (0.5ms)  SELECT  "countries".* FROM "countries" WHERE "countries"."id" =  LIMIT   [["id", 1], ["LIMIT", 1]]
ActiveRecord::RecordNotFound: Couldn't find Country with 'id'=1
    from (irb):1
irb(main):002:0> Country.find_by(id: 1)
  Country Load (0.9ms)  SELECT  "countries".* FROM "countries" WHERE "countries"."id" =  LIMIT   [["id", 1], ["LIMIT", 1]]
=> nil
irb(main):003:0> Country.find_by!(id: 1)
  Country Load (0.7ms)  SELECT  "countries".* FROM "countries" WHERE "countries"."id" =  LIMIT   [["id", 1], ["LIMIT", 1]]
ActiveRecord::RecordNotFound: Couldn't find Country
    from (irb):3

从这个例子可以看出,.find_by - rather it just returns nil. If you want to raise an exception then you need to use .find_by! instead. The same applies to dynamic finders没有引发它。

您应该使用 find_by! 引发 ActiveRecord::RecordNotFound 异常。

只有验证会引发 ActiveRecord::InvalidRecord,而不是 ActiveRecord::RecordNotFound