Hi, is there an easy way to redefine ‘while’. I have a class that uses a
while loop. In my unit test it always evaluates to false (which is
correct). I only want the loop to run once, and the enter. Just like an
if.
This is the code I’ve tried:
def while(condition)
p “redefined while!”
yield if condition
end
Hi, is there an easy way to redefine ‘while’. I have a class that uses a
while loop. In my unit test it always evaluates to false (which is
correct). I only want the loop to run once, and the enter. Just like an
if.
As others already noted, while is a keyword not a method. But
depending on how your code is structured you might be able to mock the
condition in your test:
$ cat foo.rb
class Foo
attr_reader :i
def initialize @i = 0
end
def condition @i < 10
end
def method
while condition @i += 1
end
end
end
$ cat foo_spec.rb
require ‘foo’
describe Foo do
it “should loop once” do
f = Foo.new
f.i.should == 0
f.method
f.i.should == 10
end
it “should loop once” do
f = Foo.new
f.should_receive(:condition).and_return(true, false)
f.i.should == 0
f.method
f.i.should == 1
end
end
A good idea, but isn’t working in my case. If I mock the condition I
change the behaviour of the method under test too much. But thanks
anyway!
I find your approach suspicious: you write a class with a method whose
regular behavior involves executing a loop. Then, during tests you want
the loop to not loop, i.e. you change the behavior of your method.
Strictly speaking the test result is then meaningless, because you do
not test the behavior of the method that you want to use regularly.
If there is a complex operation in the loop that you want to test
separately you should probably refactor the code. Then you can have
your one off test.
I find your approach suspicious: you write a class with a method whose
regular behavior involves executing a loop. Then, during tests you want
the loop to not loop, i.e. you change the behavior of your method.
Strictly speaking the test result is then meaningless, because you do
not test the behavior of the method that you want to use regularly.
If there is a complex operation in the loop that you want to test
separately you should probably refactor the code. Then you can have
your one off test.