Rspec:如何在私有方法中引发exception测试?
在私有方法中测试exception时出错。 如何在私有方法中引发exception,该方法是从公共方法调用的?
上市
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 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 '
我尝试改变测试用例的结构,但仍然会出错。
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 – 引发错误时参数数量错误