【问题标题】:Rspec: How to test an exception is raised in private method?Rspec:如何测试私有方法中引发的异常?
【发布时间】:2019-03-12 11:30:42
【问题描述】:

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

公开

def public_method
    private_method
end

私人

  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)

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 rspec rspec-rails


    【解决方案1】:

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

    看到这个问题我问了一段时间关于同样的问题:

    Rspec - wrong number of arguments when raising error

    【讨论】:

    • 感谢您的回复。我按照你说的尝试了,但是,它不起作用错误出现:`失败/错误:expect_any_instance_of(Product).to receive(:private_method).and_raise(Product::StaleObjectError.new(nil, nil)) ArgumentError: wrong参数数量(2 代表 0..1)`
    • Woking,我没有处理 private_method 提出的 Product::StaleObjectError。我在public_method 处理它。使用ActiveRecord::StaleObjectError.new(self, "Test") 而不是Product::StaleObjectError。谢谢@max
    猜你喜欢
    • 2019-03-09
    • 2015-11-28
    • 2019-03-09
    • 2014-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多