【问题标题】:Rspec: Getting error while testing private methodRspec:测试私有方法时出错
【发布时间】:2019-03-12 10:41:39
【问题描述】:

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

公开

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)

【问题讨论】:

  • @SimpleLime 原代码与这里不同。这是一个错字代码。更新的问题。
  • 你为什么使用花括号?,用括号内的产品试试。
  • @SebastianPalma 工作。多谢。你能更新你的答案吗?这样我才能接受。
  • 好的,你能告诉我你用的是什么版本的RSpec,rspec-rails吗?
  • Loading development environment (Rails 3.2.22.4) irb(main):001:0&gt; RUBY_VERSION =&gt; "1.9.3"

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-08
    • 1970-01-01
    • 2011-05-15
    • 1970-01-01
    • 2019-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多