Search code examples
rubyinspec

Undefined method 'scan' for nil:NilClass (NoMethodError)


Stuck on this one, this layout is for a chef inspec test but leveraging ruby to grab the contents of a file. However with this test I'm not actually testing against a file, so I'm trying to understand how to account for that, heres the code:

%w(/etc/bashrc /etc/profile).each do |path|
file(path).content.scan(/^\s*umask\s+(\d{3})\b/).flatten.each do |umask| 
 BASELINE = '0027'
 (1..3).each do |i| # leading char is '0' octal indicator
    describe umask[i].to_i do
        it { should be <= BASELINE[i].to_i }
     end
    end
   end
  end
end

Here is the line giving me trouble

file(path).content.scan(/^\s*umask\s+(\d{3})\b/).flatten.each do |umask|

Solution

  • As far as the error is concerned, i.e., "Undefined method 'scan' for nil:NilClass", this error would only come up, while doing inspec run, if the files, which are being passed, are either not present or not readable on the file system.

    Also, The information provided is not complete, as it is unclear that what is the umask set in both files, i.e, is it 3 digits or 4 digits ones?

    Because while doing scan you are looking for 3 digit umask "scan(/^\sumask\s+(\d{3})\b/)*" and you have set "BASELINE = '0027'" which is 4 digit one. So, it would definitely going to have a problem.

    If you have "umask 027" in the files, then, it should be: Check BASELINE = '027', searching 3 digit umask

    %w(/etc/bashrc /etc/profile).each do |path|
      file(path).content.scan(/^\s*umask\s+(\d{3})\b/).flatten.each do |umask| 
       BASELINE = '027'
       (1..3).each do |i| # leading char is '0' octal indicator
          describe umask[i].to_i do
            it { should be <= BASELINE[i].to_i }
          end
       end
     end
    end
    

    Else you have "umask 0027" in the files, then, it should be:

    Check scan(/^\s*umask\s+(\d{4})\b/), searching 4 digit umask

    %w(/etc/bashrc /etc/profile).each do |path|
      file(path).content.scan(/^\s*umask\s+(\d{4})\b/).flatten.each do |umask| 
       BASELINE = '027'
       (1..3).each do |i| # leading char is '0' octal indicator
          describe umask[i].to_i do
            it { should be <= BASELINE[i].to_i }
          end
       end
     end
    end