2017-07-14 26 views
0

我試圖使這個測試工作,但內部File.foreach抱怨。它找到變量a的文件,但它在那裏時無法打開它。這個構造是否使用正確的方式在另一個循環內打開文件?紅寶石file.foreach

(這不是最後的測試,我只是想獲得的東西去)

describe "2.1.18" do 
    it "CIFS: Only valid users are allowed" do 
    if File.exist?('/etc/samba/samba.d/shares.conf') 
     authorized_regexp = /^\s*(valid\s+users\s+\W{1}\s+.+)/ 
     path_regexp = /path/ 
     inc_regexp = /^\s*include/ 
     path_count = 0 
     a_count = 0 

     File.foreach('/etc/samba/samba.d/shares.conf') do |line| 
     if mtch = line.match(authorized_regexp) 
      a_count += 1 
     else 
      if mtch = line.match(inc_regexp) 
      _, a = line.split('=') 
      File.foreach(a) do |pp| 
       if mtch = pp.match(authorized_regexp) 
       a_count += 1 
       end 
      end 
      end 
     end 
     if mtch = line.match(path_regexp) 
      path_count += 1 
     end 
     end 
     expect(a_count).to eq(path_count) 
    end 
    end 
end 

錯誤消息 規範2.1.18

BIDET CIFS: Only valid users are allowed (FAILED - 1) 
Failures: 

    1) 2.1.18 CIFS: Alleen geautoriseerde gebruikers hebben toegang 
Failure/Error: File.foreach(a) do |pp| 
Errno::ENOENT: 

    No such file or directory @ rb_sysopen - /etc/samba/liv_smb.conf 
# ./test_spec.rb:16:in `foreach' 
# ./test_spec.rb:16:in `block (3 levels) in <top (required)>' 
# ./test_spec.rb:10:in `foreach' 
# ./test_spec.rb:10:in `block (2 levels) in <top (required)>' 
Finished in 0.00119 seconds (files took 0.11126 seconds to load) 
1 example, 1 failure 

文件不能打開。

# ls -l /etc/samba/liv_smb.conf 

-rw-r--r-- 1 root root 247 Jul 14 09:49 /etc/samba/liv_smb.conf 

編輯

mudasobwa解決這個問題,File.foreach(a.strip)的伎倆!

+0

'File.foreach(a.strip)'應該有幫助,我相信它有一個尾隨的'\ n'。 – mudasobwa

+0

你統治!就是這樣,非常感謝。 –

+0

值得一提的是,作爲一個自我回答,因爲它關閉了這個問題的循環,並可以幫助其他人在同一個擁堵。 – tadman

回答

0

mudasobwa提供瞭解決方案,因爲它包含換行符,所以我需要將'strip'添加到'a'變量。

 File.foreach(a.strip) do |pp| 
      if mtch = pp.match(authorized_regexp) 
      a_count += 1 
      end 
     end