techraf techraf - 2 years ago 3105
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')

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

However, when I run
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')
undefined method `[]' for nil:NilClass

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

I use Serverspec's default
. For reference full git repository with Vagrant machine.

is as below, although the test fails regardless of the contents:


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

What can be wrong?

Answer Source

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')

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download