Rspec-预期的ActiveRecord :: RecordInvalid但未引发任何问题?

时间:2019-01-10 03:59:38

标签: ruby-on-rails ruby ruby-on-rails-4 rspec

我正在使用rspec创建测试,并尝试引发错误“ ActiveRecord :: RecordInvalid”,但我一直收到“预期的ActiveRecord :: RecordInvalid但未引发任何错误”

我对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

2 个答案:

答案 0 :(得分:2)

那是错误的例外。

记录无效时引发

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时并不会引发它-而是调用.save!.create!的“ bang”方法时。

您可能需要的是ActiveRecord::RecordNotFound

irb(main):001:0> Country.find(1)
  Country Load (0.5ms)  SELECT  "countries".* FROM "countries" WHERE "countries"."id" = $1 LIMIT $2  [["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" = $1 LIMIT $2  [["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" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
ActiveRecord::RecordNotFound: Couldn't find Country
    from (irb):3

从本示例中可以看到,.find_by并未引发它-而是返回nil。如果要引发异常,则需要使用.find_by!dynamic finders也是如此。

答案 1 :(得分:1)

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

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