gpt4 book ai didi

ruby-on-rails - Rspec - 预期 ActiveRecord::RecordInvalid 但没有引发任何问题?

转载 作者:太空宇宙 更新时间:2023-11-03 18:03:54 27 4
gpt4 key购买 nike

我正在使用 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

最佳答案

那是错误的异常。

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 时它不会被引发。 - 但它是当你调用“bang”方法时 .save!.create! .

您可能正在寻找的是 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 引发的。 - 而只是返回零。如果您想引发异常,则需要使用 .find_by! 代替。同样适用于dynamic finders .

关于ruby-on-rails - Rspec - 预期 ActiveRecord::RecordInvalid 但没有引发任何问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54121785/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com