Rspec - 需要存根在另一个文件中调用的File.open

Sha*_*tel 12 ruby testing rspec mocking stubbing

在我的测试中,我正在初始化一个Package带有一些参数的新类.

在这个类的初始化中,我打开了一个在我的远程盒子上可用的文件,但不是本地常见的文件.我想知道如何在测试中使用该方法.

我正在使用rspec和mocha.我尝试过类似的东西:

File.stubs(:open).with(:file).returns(File.open("#{package_root}/test_files/test.yml"))
Run Code Online (Sandbox Code Playgroud)

Package在我的测试中初始化之前,我有这条线.

我收到了这个错误:

unexpected invocation: File.open('package/test_files/test.yml')
   satisfied expectations:
   - allowed any number of times, not yet invoked: File.open(:file)
Run Code Online (Sandbox Code Playgroud)

我不熟悉rspec或mocha,所以请帮助.谢谢!

Chr*_*zie 16

存根的新语法如下所示:

allow(File).to receive(:open).with('file_name').and_return(file_like_object)
Run Code Online (Sandbox Code Playgroud)


Dan*_*ett 10

我不确定你是否需要那个.with(:file)部分,试着完全放弃它.此外,我相信通过指定它,你实际上告诉它期望有人调用该方法并传递 :file符号而不是例如字符串文件名.还要考虑预加载测试YAML文件,然后返回:

let(:file_like_object) { double("file like object") }

File.stub(:open).and_return(file_like_object)
Run Code Online (Sandbox Code Playgroud)