Rspec - 引发错误时参数数量错误

时间:2021-06-22 19:01:39

So in my code I have this method I'm trying to test:

所以在我的代码中我有这个方法我试图测试:

  # checks if a file already exists on S3
  def file_exists?(storage_key)
    begin
      s3_resource.bucket(@bucket).object(storage_key).exists?
    rescue Aws::S3::Errors::Forbidden => e
      false
    end
  end

Now I am trying to make two test cases - one for when the file exists, and one for when it doesn't.

现在我试图制作两个测试用例 - 一个用于文件存在时,一个用于何时不存在。

Focusing on the failure case. I want to stub out the exists? to raise the Aws::S3::Errors::Forbidden error so that the file_exists? method will return false.

专注于失败案例。我想要存根存在?提出Aws :: S3 :: Errors :: Forbidden错误以便file_exists?方法将返回false。

Here's what my test code looks like:

这是我的测试代码的样子:

  it "returns false if the file doesn't already exist" do
    allow_any_instance_of(Aws::S3::Object).to receive(:exists?).and_raise(
      Aws::S3::Errors::Forbidden
    )
    expect(instance.file_exists?('foo')).to be false
  end

Running this test I see this:

运行此测试我看到:

   wrong number of arguments (given 0, expected 2)
   # ./lib/s3_client_builder.rb:48:in `file_exists?'

Really not clear what's going on here, since the file_exists? method definitely doesn't have an arity of 2 nor does the exists? method I'm stubbing.

真的不清楚这里发生了什么,因为file_exists?方法肯定没有2的arity也不存在?方法我是顽固的。

To diagnose this, I put a breakpoint in the begin block. I try and run the <object>.exists? line and get the same error.

为了诊断这个,我在begin块中放了一个断点。我尝试运行 .exists?行并得到相同的错误。

1 个解决方案

#1


13  

It turns out the problem was with:

原来问题是:

and_raise(
  Aws::S3::Errors::Forbidden
)

Running this shows the same error:

运行此操作显示相同的错误:

raise(Aws::S3::Errors::Forbidden)

What does work is this:

这是什么工作:

raise(Aws::S3::Errors::Forbidden.new(nil, nil))

#1


13  

It turns out the problem was with:

原来问题是:

and_raise(
  Aws::S3::Errors::Forbidden
)

Running this shows the same error:

运行此操作显示相同的错误:

raise(Aws::S3::Errors::Forbidden)

What does work is this:

这是什么工作:

raise(Aws::S3::Errors::Forbidden.new(nil, nil))