我试图在rspec 3.0中掌握新的allow语法(用于存根),并且非常感谢有人看着我的代码并告诉我它是对(或错)。< / p>
download.rb
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
download_spec.rb
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
非常感谢提前!
答案 0 :(得分:0)
我相信你在RSpec 3.0中使用了正确的存根语法,但我怀疑你在这种情况下使用它的动机。我强烈建议您查看Sandi Metz关于Ruby测试的演示文稿,这有助于澄清实际使用存根的适当情况。这是Sandi的Magic Tricks of Testing幻灯片。
根据您的测试名称,您真正应该测试的是文件对象是否是作为此方法的结果而创建的。这是您应该关注的唯一事项 - 将#download_file
消息发送到download
对象的直接公共副作用。除此之外的任何事情意味着您测试实现而不是接口。
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
编辑:我忘记提及的一件事是,您可能需要在此处澄清您的问题或您的测试概念,以确定这些是用于单元测试还是集成测试。这可能会改变答案。