LoginSignup
24
22

More than 5 years have passed since last update.

serverspecでMySQLの設定を検査する抹茶ー

Posted at

さくっとマッチャー書いた。
数行なので、プルリクしたもんかどうか迷う...。
failure messageを少し頑張った。

mysql_conf_matcher.rb
RSpec::Matchers.define :have_mysql_entry do |entry|
  match do |subject|
    if subject.class.name == 'Serverspec::Type::File'
      @content = subject.content
      if @value
        !! @content.lines.find {|line| line =~ /^\s*#{entry}\s*=\s*#{@value}\s*$/ }
      else
        !! @content.lines.find {|line| line =~ /^\s*#{entry}\s?=/ }
      end
    else
      raise "have_mysql_entry matcher should target to file resource"
    end
  end

  chain :with_value do |value|
    @value = value
  end

  failure_message_for_should do |actual|
    if @value
      m = "expected #{actual.to_s} to have mysql entry #{entry.inspect} with value #{@value.inspect}"
      if match = @content.match(/^(\s*#{entry}\s?=.*)/)
        m << "\n    entry #{match[1].inspect} exists, but value not matched."
      end
    else
      m = "expected #{actual.to_s} to have mysql entry #{entry.inspect}"
    end
    m
  end
end

こう使う。

sample_spec.rb
describe file('/etc/my.cnf') do
  it { should be_file }
  it { should have_mysql_entry('default-character-set').with_value('utf8') }
end
24
22
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
22