Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby rspec 3.0存根语法-不确定是否正确_Ruby_Stub_Rspec3 - Fatal编程技术网

Ruby rspec 3.0存根语法-不确定是否正确

Ruby rspec 3.0存根语法-不确定是否正确,ruby,stub,rspec3,Ruby,Stub,Rspec3,我正在努力掌握rspec3.0中stubing的新allow语法,如果有人看我的代码并告诉我它是对的还是错的,我会非常感激 下载.rb 下载_spec.rb 非常感谢 我相信您在RSpec 3.0中使用了正确的stubing语法,但我怀疑您在这种情况下使用它的动机。我强烈建议您查看Sandi Metz关于Ruby测试的演示,这将有助于澄清实际使用存根的适当情况。这是桑迪的幻灯片 根据测试的名称,似乎您真正应该测试的是是否创建了文件对象作为此方法的结果。这是您应该关心的唯一一件事,即将downlo

我正在努力掌握rspec3.0中stubing的新allow语法,如果有人看我的代码并告诉我它是对的还是错的,我会非常感激

下载.rb

下载_spec.rb


非常感谢

我相信您在RSpec 3.0中使用了正确的stubing语法,但我怀疑您在这种情况下使用它的动机。我强烈建议您查看Sandi Metz关于Ruby测试的演示,这将有助于澄清实际使用存根的适当情况。这是桑迪的幻灯片

根据测试的名称,似乎您真正应该测试的是是否创建了文件对象作为此方法的结果。这是您应该关心的唯一一件事,即将download_file消息发送到下载对象会产生直接的公共副作用。除此之外,还需要测试实现,而不是接口


编辑:我忘记提到的一件事是,您可能需要在这里澄清您的问题,或者您对测试的概念,以确定这些测试是作为单元测试还是集成测试。这可能会改变答案。

嗨,dnunez24,有趣的是,你应该这么说Sandi Metz的演讲,因为我今天早上才在YouTube上看到她谈论这个话题!我可能对我的代码不够清楚,但是对下载方法的测试实际上应该测试作为下载实现的结果而创建的文件是否存在。我会再回去看看桑迪的甲板。谢谢你的帮助!好的,很好。因此,实际上可能需要存根的是实际获取和创建文件的代码。尤其是在运行测试时可能会很耗时的情况下。如果不理解代码中涉及的其他依赖项,我很难给出一个很好的例子。您可能希望了解依赖项注入,以便更容易地将存根发送到方法调用中。我相信桑迪也给出了一些例子。
class Download
  def download_file
    # code to download a file 
  end

  def valid_json
    # code to verify downloaded file is file type json
  end
end
require 'spec_helper'
require 'json_spec'  

describe Download do 
  let(:download)  {Download.new}

  describe "#download_file" do
    it 'downloads a file from remote file location ' do
      allow(download).to receive(:exist).and_return(true)
      download.download_file
      expect(download).to have_received(:exist).and_return(true)    
    end 
  end   

  describe "#valid_json" do
    it 'confirms downloaded file is JSON' do
      # download.to_json.should have_json_path("id")
      # download.to_json.should have_json_type(Integer).at_path("id")
      expect(download.to_json).to have_json_path("id")
      expect(download.to_json).to have_json_type(Integer).at_path("id")
    end 
  end
end  
describe Download do 
  let(:download) { Download.new }

  describe "#file" do
    context "before file has been downloaded" do
      it "returns nil" do
        expect(download.file).to be_nil
      end
    end
  end

  describe "#download_file" do
    it 'downloads a file from remote file location ' do
      # incoming command message to object under test
      download.download_file
      # assert direct public side effect
      expect(download.file).to be_a File
    end 
  end   
end