2015/10/30

自作gemのテストを test-unit で行う

久しぶりに自作 gem でも作るかと bundle gem -t とすると自動的に spec フォルダと .rspec が作成された。
いやいや、test-unit 使いたいんだってば。
仕方ないので自分で設定することに
gemspec に spec.add_development_dependency 'test-unit' を追加し、Rakefile にこんな感じに設定を書くだけだった。
require 'bundler/gem_tasks'
require 'rake/testtask'
Rake::TestTask.new do |t|
t.libs << 'test'
t.test_files = FileList['test/my_gem/*_test.rb']
t.verbose = true
end
task default: :test
view raw Rakefile hosted with ❤ by GitHub

2015/10/27

自作クラスの配列同士で引き算を正しく動作させるには

class Point
attr_reader :x, :y
def initialize(x, y)
@x = x
@y = y
end
def ==(other)
@x == other.x && @y == other.y
end
def to_s
"(#{x}, #{y})"
end
def inspect
to_s
end
end
p [Point.new(1, 1), Point.new(2, 2), Point.new(3, 3)] - [Point.new(3, 3), Point.new(1, 1)]
# => [(1, 1), (2, 2), (3, 3)]
class Point
attr_reader :x, :y
def initialize(x, y)
@x = x
@y = y
end
def ==(other)
eql?(other)
end
def eql?(other)
@x == other.x && @y == other.y
end
def hash
@x + @y
end
def to_s
"(#{x}, #{y})"
end
def inspect
to_s
end
end
p [Point.new(1, 1), Point.new(2, 2), Point.new(3, 3)] - [Point.new(3, 3), Point.new(1, 1)]
# => [(2, 2)]
自作の配列で引き算を行おうとしたら、==のオーバーライドだけでは足りず、eql?hashのオーバーライドが必要だった。