alias を使っている場合の spec ファイルの書き方
ERB::Util::h() は、ERB::Util::html_escape() への alias となっている。
class ERB
module Util
module_function
def html_escape(s)
s.to_s.gsub(/&/,'&').gsub(/</,'<').gsub(/>/,'>').gsub(/"/,'"')
end
alias h html_escape
end
end
このような場合は、spec ファイルも共通化するようだ。
とりあえず spec/ruby/1.8/time/{rfc2822,rfc822}_spec.rb を参考にして、書いてみた。
spec/ruby/1.8/erb/util/shared/html_escape.rb:
shared :erb_util_html_escape do |cmd|
describe "ERB::Util.#{cmd}" do
it "escape '& < > \"' to '& < > "" do
input = '& < > "'
expected = '& < > "'
ERB::Util.__send__(cmd, input).should == expected
end
it "not escape characters except '& < > \"'" do
input = (0x20..0x7E).to_a.collect {|ch| ch.chr}.join('')
expected = input.gsub(/&/,'&').gsub(/</,'<').gsub(/>/,'>').gsub(/"/,'"')
ERB::Util.__send__(cmd, input).should == expected
end
end
end
spec/ruby/1.8/erb/util/html_escape_spec.rb:
require 'erb' require File.dirname(__FILE__) + '/../../../spec_helper' require File.dirname(__FILE__) + '/shared/html_escape' describe "ERB::Util.html_escape" do it_behaves_like :erb_util_html_escape, :html_escape end
spec/ruby/1.8/erb/util/h_spec.rb:
require 'erb' require File.dirname(__FILE__) + '/../../../spec_helper' require File.dirname(__FILE__) + '/shared/html_escape' describe "ERB::Util.h" do it_behaves_like :erb_util_html_escape, :h end
実行してみる。
$ bin/ci spec/ruby/1.8/erb/util Started .... Finished in 0.093402 seconds 4 examples, 4 expectations, 0 failures, 0 errors
成功したようだ。
しかし、これでほんとにテストされているのかどうか気になる。
そこで、h_spec.rb で ERB::Util.h() を書き換えてみる。
require 'erb'
require File.dirname(__FILE__) + '/../../../spec_helper'
require File.dirname(__FILE__) + '/shared/html_escape'
## 追加
module ERB::Util
module_function
def h(arg)
arg.to_s
end
end
describe "ERB::Util.h" do
it_behaves_like :erb_util_html_escape, :h
end
これで実行してみる。
$ bin/ci spec/ruby/1.8/library/erb/util
Started
FF..
1)
ERB::Util.h escape '& < > "' to '& < > " FAILED
Expected "& < > \"" to equal "& < > "":
Expectation.fail_with at ./mspec/expectations.rb:10
PositiveOperatorMatcher#== at ./mspec/matchers/base.rb:19
Proc#call at kernel/core/proc.rb:81
(...snip....)
Object#__script__ at kernel/loader.rb:178
2)
ERB::Util.h not escape characters except '& < > "' FAILED
Expected " !\"\#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
to equal " !"\#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~":
Expectation.fail_with at ./mspec/expectations.rb:10
PositiveOperatorMatcher#== at ./mspec/matchers/base.rb:19
(...snip....)
Object#__script__ at kernel/loader.rb:178
Finished in 0.095605 seconds
4 examples, 4 expectations, 2 failures, 0 errors
よかった、ちゃんとエラーになっているようだ。