gpt4 book ai didi

ruby - RSpec should_receive 没有到达类中的方法

转载 作者:行者123 更新时间:2023-11-28 21:32:18 26 4
gpt4 key购买 nike

ruby/rspec 的新手并尝试测试方法是否会引发异常。我可能完全错误地解决了这个问题。

#require 'rspec'

describe "TestClass" do
it "should raise exception when my method is called" do
test = Test.new
test.should_receive(:my_method).and_raise
end
end

class Test
def my_method
raise
end
end


rspec test.rb
F

Failures:

1) TestClass should raise exception when my method is called
Failure/Error: test.should_receive(:my_method).and_raise
(#<Test:0x007fc61c82f7c8>).my_method(any args)
expected: 1 time
received: 0 times
# ./test.rb:6:in `block (2 levels) in <top (required)>'

Finished in 0.00061 seconds
1 example, 1 failure

Failed examples:

rspec ./test.rb:4 # TestClass should raise exception when my method is called

为什么消息接收次数为零?

最佳答案

你的测试是错误的。为了测试是否引发了异常,您需要这样做:

it "should raise exception when my method is called" do
test = Test.new
test.should_receive(:my_method)

expect {
test.my_method
}.to raise_error
end

在这种情况下,您可能不需要添加 should_receive。通过调用 my_method,您可以确保 test 正在接收该方法。基本上,当您不需要 mock 时,您就是在 mock 。

关于ruby - RSpec should_receive 没有到达类中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15166354/

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