#276 Testing Time & Web Requests
It can be difficult to test code that deals with the current time or an external web request. Here I show you how to do both using the Timecop and FakeWeb gems.
- Download:
- source codeProject Files in Zip (112 KB)
- mp4Full Size H.264 Video (16.4 MB)
- m4vSmaller H.264 Video (9.81 MB)
- webmFull Size VP8 Video (10.8 MB)
- ogvFull Size Theora Video (26 MB)
Resources
Alternative Libraries
Gemfile
group :test do
gem "timecop"
gem "fakeweb"
end
group :test do gem "timecop" gem "fakeweb" end
spec_helper.rb
FakeWeb.allow_net_connect = false
RSpec.configure do |config|
config.before(:each) do
Timecop.return
FakeWeb.clean_registry
end
end
FakeWeb.allow_net_connect = false RSpec.configure do |config| config.before(:each) do Timecop.return FakeWeb.clean_registry end end
user_spec.rb
it "saves the time the password reset was sent" do
Timecop.freeze
user.send_password_reset
Time.use_zone("Paris") do
user.reload.password_reset_sent_at.should eq(Time.zone.now)
end
end
it "saves the time the password reset was sent" do Timecop.freeze user.send_password_reset Time.use_zone("Paris") do user.reload.password_reset_sent_at.should eq(Time.zone.now) end end
web_request_spec.rb
it "fetches the content length" do
FakeWeb.register_uri(:head, "http://example.com/", :content_length => 123)
WebRequest.new(:url => "http://example.com/").content_length.should eq(123)
end
it "fetches the content length" do FakeWeb.register_uri(:head, "http://example.com/", :content_length => 123) WebRequest.new(:url => "http://example.com/").content_length.should eq(123) end
models/web_request.rb
def content_length
uri = URI.parse(url)
response = Net::HTTP.start(uri.host, uri.port) { |http| http.request_head(uri.path) }
response["content-length"].to_i
end
def content_length uri = URI.parse(url) response = Net::HTTP.start(uri.host, uri.port) { |http| http.request_head(uri.path) } response["content-length"].to_i end
config/application.rb
require 'net/http'
require 'net/http'
