For loop in serverspec

1.3k Views Asked by At

I have this Spec file:

require 'spec_helper'

for i in 1..3
   describe file ("/var/tmp/efl_test_0#{i}_link" )do
      it { should be_linked_to "/tmp/efl_test_0#{i}" }
   end
end

The expected results are:

   /var/tmp/efl_test01_link should be_linke_to /tmp/efl_test01
   /var/tmp/efl_test02_link should be_linke_to /tmp/efl_test02
   /var/tmp/efl_test03_link should be_linke_to /tmp/efl_test03

The actual results are:

 Failure/Error: it { should be_linked_to "/tmp/efl_test_0#{i}" }
   stat -c %N /var/tmp/efl_test_01_link | egrep -e "-> ./tmp/efl_test_03."
 Failure/Error: it { should be_linked_to "/tmp/efl_test_0#{i}" }
   stat -c %N /var/tmp/efl_test_02_link | egrep -e "-> ./tmp/efl_test_03."
 Failure/Error: it { should be_linked_to "/tmp/efl_test_0#{i}" }
   stat -c %N /var/tmp/efl_test_03_link | egrep -e "-> ./tmp/efl_test_03."

Each link is compared to the 03 target. The problem is something about the loop I guess.

What have I done wrong?

2

There are 2 best solutions below

1
On

This could be an artifact of how i is captured as a closure and lazy-evaluated by describe later on. At that point it's been incremented. You may need to deliberately capture it:

for i in 1..3
  path = "/tmp/efl_test_0#{i}"
  describe file ("/var/tmp/efl_test_0#{i}_link" )do
    it { should be_linked_to path }
  end
end

Normally you'd use 3.times do to be more conventional Ruby. The for construct is hardly ever used.

1
On

This works:

require 'spec_helper'

3.times do |i|
   describe file ("/var/tmp/efl_test_0#{i+1}_link" )do
      it { should be_linked_to "/tmp/efl_test_0#{i+1}" }
   end
end

Results:

    rspec ./spec/localhost/025_efl_test.rb:5 # 
File "/var/tmp/efl_test_01_link" should be linked to "/tmp/efl_test_01"
    rspec ./spec/localhost/025_efl_test.rb:5 # 
File "/var/tmp/efl_test_02_link" should be linked to "/tmp/efl_test_02"
    rspec ./spec/localhost/025_efl_test.rb:5 # 
File "/var/tmp/efl_test_03_link" should be linked to "/tmp/efl_test_03"