From cfa824c9091d4e33d3c7b3578a68849837105195 Mon Sep 17 00:00:00 2001 From: Kanezoh Date: Tue, 24 Aug 2021 08:09:43 +0900 Subject: [PATCH] download file within transact --- spec/agent_spec.cr | 16 +++++++++------- src/mechanize.cr | 12 ++++++------ 2 files changed, 15 insertions(+), 13 deletions(-) diff --git a/spec/agent_spec.cr b/spec/agent_spec.cr index ed7e8f8..86b7300 100644 --- a/spec/agent_spec.cr +++ b/spec/agent_spec.cr @@ -57,13 +57,6 @@ describe "Mechanize Agent test" do agent2.history.pop.uri.to_s.should eq "http://example.com/form" end - it "can download page" do - agent = Mechanize.new - agent.download("http://example.com", "mechanizecr_example.html") - File.exists?("mechanizecr_example.html").should eq true - File.delete("mechanizecr_example.html") - end - it "doesn't add page to history within transact block" do agent = Mechanize.new agent.get("http://example.com/") @@ -73,4 +66,13 @@ describe "Mechanize Agent test" do end agent.history.size.should eq 1 end + + it "can download page" do + agent = Mechanize.new + agent.history.size.should eq 0 + agent.download("http://example.com", "mechanizecr_example.html") + agent.history.size.should eq 0 + File.exists?("mechanizecr_example.html").should eq true + File.delete("mechanizecr_example.html") + end end diff --git a/src/mechanize.cr b/src/mechanize.cr index 3bd9b7a..6fcf332 100644 --- a/src/mechanize.cr +++ b/src/mechanize.cr @@ -130,13 +130,13 @@ class Mechanize filename, headers = HTTP::Headers.new, params : Hash(String, String | Array(String)) = Hash(String, String).new) - page = get(uri, headers, params) - - case page - when MechanizeCr::File - File.write(filename, page.body) + transact do + page = get(uri, headers, params) + case page + when MechanizeCr::File + File.write(filename, page.body) + end end - page end # Runs given block, then resets the page history as it was before.