gpt4 book ai didi

ruby-on-rails - RSpec 中的 'expect' 和 'should' 之间有区别吗?

转载 作者:行者123 更新时间:2023-12-04 06:17:49 24 4
gpt4 key购买 nike

例如,这两个测试:

it "fails to create given a bad player list" do
Team.new("Random name", bad_players).should raise_error
end


it "fails to create given a bad player list" do
expect {Team.new("Random name", bad_players)}.to raise_error
end

它们返回不同的输出(第一个失败,而第二个通过)。根据 Team 模型的内容,我希望两者都通过或失败。

完整的 RSpec 代码是:
require_relative 'team'

describe "Team" do

it "has a name" do
Team.new("Random name").should respond_to(:name)
end

it "has a list of players" do
Team.new("Random name").players.should be_kind_of Array
end

it "is favored if it has a celebrity on it"
it "complains if there is a bad word in the name"

context "given a bad list of players" do
let(:bad_players) { {} }

it "fails to create given a bad player list" do
expect { Team.new("Random name", bad_players) }.to raise_error
end
end

end

我认为“应该”会起作用的原因是因为“它有一个名字”测试中有类似的语法。如果事实证明“应该”是不正确的,而“期望...到”是正确的,我很想知道何时使用一个与另一个。谢谢。

最佳答案

引自 https://github.com/rspec/rspec-expectations/blob/master/Should.md :

From the beginning RSpec::Expectations provided should and should_not methods to define expectations on any object. In version 2.11 expect method was introduced which is now the recommended way to define expectations on an object.



该文档中的下一段描述了实现上的差异以及原因 expect现在是推荐的方法。

在这一点上,几乎可以用 should 做任何事情。和 should_not可以用 expect 来完成.见 http://rubydoc.info/gems/rspec-expectations/frames详情和 expect用法。

至于您的特定代码,第一个示例失败的原因是错误发生在 RSpec 有机会参与之前。您仍然可以使用 should检查是否引发错误,但您必须给 RSpec 一个工作的机会。语法是 lambda {...}.should raise_error哪里 ...是您正在测试的代码。

关于ruby-on-rails - RSpec 中的 'expect' 和 'should' 之间有区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18070765/

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