techraf techraf - 5 months ago 29
Ruby Question

"undefined method `[]' for nil:NilClass" error when running Serverspec test remotely

I have a Serverspec test using inifile gem:

require 'spec_helper'
require 'inifile'

describe 'inifile test -' do
file = '/tmp/testfile1.ini'
file_ini = IniFile.load(file)
it 'testfile1.ini should contain expected values' do
expect(file_ini['section1']['variable1']).to eq('value1')
end
end


The test passes if
rake
is executed locally on the machine (either on Ubuntu guest or OS X host, where
inifile
gem is installed).

However, when I run
rake
against Vagrant box (i.e. on host connecting with SSH to Ubuntu on Vagrant) it fails with the following message:

1) inifile test - testfile1.ini should contain expected values
On host `molecule-test'
Failure/Error: expect(file_ini['section1']['variable1']).to eq('value1')
NoMethodError:
undefined method `[]' for nil:NilClass

# ./spec/inifile_spec.rb:8:in `block (2 levels) in <top (required)>'


I use Serverspec's default
Rakefile
and
spec_helper.rb
. For reference full git repository with Vagrant machine.

/tmp/testfile1.ini
is as below, although the test fails regardless of the contents:

[section1]
variable1=value1


It seems to me like some kind of problem with characters not-escaped, but I am not really sure.

What can be wrong?

Answer

After ensuring that inifile is installed on the Vagrant instance:

file_ini = command("ruby -rinifile -e \"IniFile.load(file)\"")

This will get you started. A rather inelegant way of doing this would be something like this:

describe 'inifile test -' do
  file_ini = command("ruby -rinifile -e \"print IniFile.load('/tmp/testfile1.ini')['section1']['variable1']\"").stdout
  it 'testfile1.ini should contain expected values' do
    expect(file_ini).to eq('value1')
  end
end

I do not know if the file variable scope would work inside of that command method, so I played it safe.

Comments