rubyvagrantrakeserverspec

"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.

/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?


Solution

  • After ensuring that inifile is installed on the Vagrant instance, 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.

    Asker techraf adds this cleaner route given a good knowledge of the inifile API.

    describe 'inifile test -' do
      file_ini = IniFile.new(content: command("cat /tmp/testfile1.ini").stdout)
      it 'testfile1.ini should contain expected values' do
        expect(file_ini['section1']['variable1']).to eq('value1')
      end
    end
    

    With some collaboration, we arrive at this hopefully optimal solution.

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