gpt4 book ai didi

ruby-on-rails - 将更清晰的描述传递给 RSpec `its` 方法

转载 作者:行者123 更新时间:2023-11-28 19:52:47 24 4
gpt4 key购买 nike

我是 RSpec 的新手,但我真的很喜欢编写测试的简单性,并且在我学习 RSpec 的新功能时不断重构它们以使其更清晰。所以,最初,我有以下内容:

describe Account do
context "when new" do
let(:account) { Account.new }
subject { account }

it "should have account attributes" do
subject.account_attributes.should_not be_nil
end
end
end

然后我了解了 its 方法,所以我尝试这样重写它:

describe Account do
context "when new" do
let(:account) { Account.new }
subject { account }

its(:account_attributes, "should not be nil") do
should_not be_nil
end
end
end

由于 its 不接受 2 个参数而失败,但是删除消息工作正常。问题是,如果测试失败,失败示例部分下的消息只是说

rspec ./spec/models/account_spec.rb:23 # Account when new account_attributes

这并不过分帮助。

那么,有没有一种方法可以将消息传递给 its,或者更好的是,让它自动输出一条理智的消息?

最佳答案

您可以定义一个 RSpec 自定义匹配器:

RSpec::Matchers.define :have_account_attributes do
match do |actual|
actual.account_attributes.should_not be_nil
end
failure_message_for_should do
"expected account_attributes to be present, got nil"
end
end

describe Account do
it { should have_account_attributes }
end

关于ruby-on-rails - 将更清晰的描述传递给 RSpec `its` 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12426907/

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