0

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?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Neil H Watson
  • 1,002
  • 1
  • 14
  • 31

2 Answers2

2

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.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • 1
    That is odd. Both of those strings should be evaluated immediately. Try using `3.times do |i|` and then using `#{i+1}` in place as the default is zero-indexed. I think the problem here might be how `for` doesn't have the right scoping. – tadman Dec 15 '14 at 16:55
1

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"
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Neil H Watson
  • 1,002
  • 1
  • 14
  • 31
  • Please don't use answers to converse with people. Stack Overflow isn't a conversation board; It's a reference site. If @tadman's answer helped you solve the problem, then select his answer. It isn't necessary to show what changes you made, either in a separate answer or in your own. If you, on your own, discovered the answer, then select your answer. Either way, if you have found a solution, mark whichever answer contributed so we can tell the answer has been found. – the Tin Man Dec 15 '14 at 17:39