ImageMagick のコマンドで 2 つの画像を比較して差分を抽出できる機能があることを知りました。
2枚の画像のdiff(差分)を超簡単に調べる方法
http://blog.mirakui.com/entry/20110326/1301111196
これをテストで使ってみたくて下記のように RSpec を作りました。
screenshotdiff_spec.rb
require 'watir-webdriver'
describe "Screenshot" do
before do
@browser = Watir::Browser.new :ff
end
it "development and production are the same" do
@browser.goto "http://development.example.com"
@browser.screenshot.save "development.png"
@browser.goto "http://production.exapmle.com"
@browser.screenshot.save "production.png"
`composite -compose difference development.png production.png diff.png`
result = `identify -format "%[mean]" diff.png`
expect(result).to eq("0\n")
end
after do
@browser.close
end
end
説明
Firefox を起動して http://development.example.com
と http://production.exapmle.com
をそれぞれ開き、それぞれのスクリーンショットをカレントディレクトリに保存します。保存した 2 つのスクリーンショットを composite
コマンドを使って画像の差分を可視化します。そして identify
コマンドを使って差分の有無を検出し、その結果を expect
でテストします。
気がついたこと
- ウェブサイトのほとんどは動的にコンテンツが生成されており全く差分が無いことはまず無い。なので、自動テストに組み込むのであれば、ある程度の差分を許すようなアプローチが必要。(画像認識?)
- selenium-webdriver でも試したが、画像が完全に同一となるような同じ URL のスクリーンショットを撮っても、ロードのタイミングのせいなのか差分が発生してしまった。watir-webdriver だとうまくスクリーンショットが撮れた。