2014-11-01 Sat

[別の年の同じ日: 2002 2004 2005 2006 2007 2008 2009 2010

Serverspec で Encoding::CompatibilityError はてぶ

覚え書き

環境
- OS: Solaris 11.2
- Ruby: 2.1.3
- Serverspec: 2.3.1
- Specinfra: 2.4.1

問題

以下のような match 部分

describe file('hoge.txt') do
  its(:content){ should match(/日本語/) }
end



     Encoding::CompatibilityError:
       incompatible encoding regexp match (UTF-8 regexp with ASCII-8BIT string)


が出る。

回避方法

lib/serverspec/type/file.rb で以下のように @content ではなく @content.force_encoding('UTF-8') を返す。

    def content
      if @content.nil?
        @content = @runner.get_file_content(@name).stdout
      end
      @content.force_encoding('UTF-8')
    end


これだと乱暴なので、
以下のように書けるようにする方向で考えた方がよさげ。

describe file('hoge.txt') do
  its(:content){ should match(/日本語/).with_encoding('UTF-8') }
end