Skip to content
Browse files

Use options_or_mode in new_fd and new_io helpers.

  • Loading branch information...
1 parent 474478d commit 64ece89b5c03e6d8dcf1574beb9ffa8a82f7e7b9 @brixen brixen committed Oct 18, 2012
Showing with 45 additions and 3 deletions.
  1. +12 −2 mspec/lib/mspec/helpers/io.rb
  2. +33 −1 mspec/spec/helpers/io_spec.rb
View
14 mspec/lib/mspec/helpers/io.rb
@@ -27,13 +27,23 @@ class Object
# with any Ruby object). The file descriptor can safely be passed
# to IO.new without creating a Ruby object alias to the fd.
def new_fd(name, mode="w:utf-8")
+ mode = options_or_mode(mode)
+
+ if mode.kind_of? Hash
+ if mode.key? :mode
+ mode = mode[:mode]
+ else
+ raise ArgumentError, "new_fd options Hash must include :mode"
+ end
+ end
+
IO.sysopen name, fmode(mode)
end
# Creates an IO instance for a temporary file name. The file
# must be deleted.
def new_io(name, mode="w:utf-8")
- IO.new new_fd(name, fmode(mode)), fmode(mode)
+ IO.new new_fd(name, options_or_mode(mode)), options_or_mode(mode)
end
# This helper simplifies passing file access modes regardless of
@@ -58,7 +68,7 @@ def options_or_mode(oom)
if FeatureGuard.enabled? :encoding
oom
else
- fmode(oom[:mode]) || "r"
+ fmode(oom[:mode] || "r:utf-8")
end
end
end
View
34 mspec/spec/helpers/io_spec.rb
@@ -50,7 +50,7 @@
end
after :each do
- @io.close unless @io.closed?
+ @io.close if @io and not @io.closed?
rm_r @name
end
@@ -64,6 +64,23 @@
IO.read(@name).should == "io data"
end
+
+ it "accepts an options Hash" do
+ FeatureGuard.stub!(:enabled?).and_return(true)
+ fd = new_fd @name, { :mode => 'w:utf-8' }
+ fd.should be_an_instance_of(Fixnum)
+
+ @io = IO.new fd, fmode('w:utf-8')
+ @io.sync = true
+ @io.print "io data"
+
+ IO.read(@name).should == "io data"
+ end
+
+ it "raises an ArgumentError if the options Hash does not include :mode" do
+ FeatureGuard.stub!(:enabled?).and_return(true)
+ lambda { new_fd @name, { :encoding => "utf-8" } }.should raise_error(ArgumentError)
+ end
end
describe Object, "#new_io" do
@@ -95,6 +112,21 @@
@io.print "io data"
IO.read(@name).should == "io data"
end
+
+ it "opens the IO for reading if passed { :mode => 'r' }" do
+ touch(@name) { |f| f.print "io data" }
+ @io = new_io @name, { :mode => "r" }
+ @io.read.should == "io data"
+ lambda { @io.puts "more data" }.should raise_error(IOError)
+ end
+
+ it "opens the IO for writing if passed { :mode => 'w' }" do
+ @io = new_io @name, { :mode => "w" }
+ @io.sync = true
+
+ @io.print "io data"
+ IO.read(@name).should == "io data"
+ end
end
describe Object, "#fmode" do

0 comments on commit 64ece89

Please sign in to comment.
Something went wrong with that request. Please try again.