gpt4 book ai didi

ruby-on-rails - Rspec:如何测试私有(private)方法中引发的异常?

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

在私有(private)方法中测试异常时出错。如何测试从公共(public)方法调用的私有(private)方法引发的异常?

公开

def public_method
private_method
end

私有(private)

  def private_method
tries = 0
begin
raise Product::StaleObjectError.new("Product is changed while you were editing") if stale_object?
// Do some work
raise Exception.new("Total amount used is greater than approved") if total_approved < 0

// Save Product
rescue Product::StaleObjectError => e
if tries < MAX_RETRIES
tries += 1
sleep(1 + tries)
reload
retry
else
raise Product::StaleObjectError("Product is changed while you were editing")
end
end
attributes
end

测试用例:

  before(:each) do
@prod_v1 = Product.new
end
it 'if product stale, then an exception should raise' do
Product.any_instance.stub(:stale_object?).and_return(true)
expect_any_instance_of(Product).to receive(:private_method).and_raise(Product::StaleObjectError.new("Product is changed while you were editing"), nil)
@prod_v1.public_method
end

测试用例出现以下错误

 Failure/Error: @product_v1.private_method
Product::StaleObjectError:
Product is changed while you were editing
# ./app/models/product.rb:10:in `private_method'
# ./spec/models/product_spec.rb:67:in `block (4 levels) in <top (required)>'

我尝试更改测试用例的结构,但仍然出错。

  it 'if product stale, then an exception should raise' do
Product.any_instance.stub(:stale_object?).and_return(true)
expect_any_instance_of(Product).to receive(:private_method).and_raise(Product::StaleObjectError.new(nil, nil))
@prod_v1.public_method
end

错误

    Failure/Error: expect_any_instance_of(Product).to receive(:private_method).and_raise(Product::StaleObjectError.new(nil, nil))
ArgumentError:
wrong number of arguments (2 for 0..1)

最佳答案

尝试 and_raise(Product::StaleObjectError.new(nil, nil))

看到这个问题我问了一会儿关于同一个问题:

Rspec - wrong number of arguments when raising error

关于ruby-on-rails - Rspec:如何测试私有(private)方法中引发的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52691340/

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