Hello everyone,
I'm trying to get to grips with the new allow syntax (for stubbing) in rspec 3.0 and would really appreciate someone looking at my code and telling me whether it's right(or wrong).
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
enddownload_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 Many thanks in advance!
Hello!
I think that on describe "#download_file" you are only testing if the stub works (and it does not make sense), besides testing if the method #download_file does what you want.
The last describe, looks dependent of the download_file execution but you didn’t run it neither stub its result.
On RSpec (or every test framework I remember), each test (it) is isolated from others, so a test can not depend of an above test (most because the order of the test can be randomly chosen, so a test must really not depend that an other test have run).
So, a better test, might be something like:
describe Download do
let(:download) {Download.new}
let(:file_path) { "http://file_path.com/test_file.json" }
let(:file_content) { "{ 'id': 1, 'content': 'blabla' }" }
before { stub_request(:get, file_path).to_return(:body => file_content) }
describe "#download_file" do
before { allow(download).to receive(:file_path).and_return(file_path) }
it 'downloads a file from remote file location ' do
download.download_file
expect(download.file_content).to eq(file_content)
end
end
describe "#valid_json" do
before { allow(download).to receive(:file_content).and_return(file_content) }
it 'confirms downloaded file is JSON' do
download.valid_json
expect(download).to have_received(:to_json)
expect(download.to_json).to have_json_path("id")
expect(download.to_json).to have_json_type(Integer).at_path("id")
expect(download.valid_json).to be_truthy
end
end
end
Have a nice hacking! :D
Carlos Figueiredo
--
You received this message because you are subscribed to the Google Groups "rspec" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rspec+un...@googlegroups.com.
To post to this group, send email to rs...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rspec/3ace07ec-b440-47e5-9c09-ce6c14109f53%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.