Rspec:测试专用方法时出错

时间:2018-10-07 16:53:54

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

在测试私有方法时出错。请建议如何从公共方法中调用私有方法。

公共

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 'test private method called' do
    expect_any_instance_of {Product}.to receive(:private_method)
    @prod_v1.public_method
  end

我在测试用例中遇到以下错误

  Failure/Error: expect_any_instance_of {Product}.to receive(:)
     ArgumentError:
       wrong number of arguments (0 for 1)

1 个答案:

答案 0 :(得分:1)

根据expect_any_instance_of的文档,它将作为方法参数接收该类,因此您应该使用括号而不是花括号:

it 'test private method called' do
  expect_any_instance_of(Product).to receive(:private_method)
  ...
end