From: Sam Ruby Date: 2008-02-06T20:58:52+09:00 Subject: Re: reopen: can't change access mode from "w+" to "w"? Nobuyoshi Nakada wrote: > Hi, > > At Wed, 6 Feb 2008 03:00:43 +0900, > Sam Ruby wrote in [ruby-core:15360]: >> require 'tmpdir' >> >> save = STDOUT.dup >> STDOUT.reopen File.open(File.join(Dir.tmpdir, "should_output_#{$$}"), "w+") >> puts 'hi' >> out = STDOUT.dup >> STDOUT.reopen save > > Here, the mode of STDOUT was changed to "w+" by previos reopen, > and this is trying to change the mode to "w" back, or "shrink" > in other words. Understood. It works with ruby 1.8.6 (2007-06-07 patchlevel 36) [i486-linux], but fails with ruby 1.9.0 (2008-02-06 revision 15384) [i686-linux]. >> Is this a bug in Ruby 1.9? If not, any suggestions on a workaround for >> test/spec? > > A workaround is to specify the mode at reopen: > > save = STDOUT.dup > out = File.open(File.join(Dir.tmpdir, "should_output_#{$$}"), "w+") > STDOUT.reopen(out, "w") > puts 'hi' > STDOUT.reopen save That doesn't work for me. When reopen is passed two parameters, the first parameter is expected to be a file name. The workaround suggested by Eero Saynatkari does work for me. I've pasted a diff in terms of the the original test/spec code below my signature. The only remaining question for me is whether this change in behavior in Ruby 1.9 is intentional, and that applications need to conform, or if it is temporary and will soon be corrected. - Sam Ruby --- old-testspec/lib/test/spec/should-output.rb 2008-02-06 06:51:50.000000000 -0500 +++ new-testspec/lib/test/spec/should-output.rb 2008-02-06 06:51:50.000000000 -0500 @@ -12,7 +12,7 @@ old_to = to.dup # Obtain a filehandle to replace (works with Readline) - to.reopen File.open(File.join(Dir.tmpdir, "should_output_#{$$}"), "w+") + to.reopen File.open(File.join(Dir.tmpdir, "should_output_#{$$}"), "w") # Execute @object.call @@ -22,8 +22,8 @@ to.reopen old_to # Grab the data - out.rewind - output = out.read + out.flush + output = File.open(out.path) {|file| file.read} # Match up case expected