-2

I need to test a method which is as below

class Something
  def test_method
   count = 0
   arr = []
   max = 500
    puts "test_method"
    loop do
      arr += count if count.even?
      count += 1
    end break if count > max
    return arr
  end
end

So basically I need to test whether test_method() return an instance of array and arr size is greater than 3. But I dont want to enter into this loop for every time and return the result. So is there any way in rspec where I can stub the max value and return the array without looping 500 times.

rubyist
  • 3,074
  • 8
  • 37
  • 69

2 Answers2

0

You can use the class_variable_set method.

class Something
  @@max = 500

  def test_method
   count = 0
   arr = []

    puts "test_method"
    loop do
      arr += count if count.even?
      count += 1
    end break if count > @@max
    return arr
  end
end

In your case, an rspec before_each block could look like this:

before(:each) { Something.class_variable_set :@@max, 20 }

You can use an instance_variable too, as described in this answer

Community
  • 1
  • 1
Srikanth Venugopalan
  • 9,011
  • 3
  • 36
  • 76
0

Perhaps it is an option to pass max as a optional argument to that method?

class Something
  def test_method(max = 500)
    count = 0
    arr = []
    puts "test_method"
    # ...
  end
end
spickermann
  • 100,941
  • 9
  • 101
  • 131
  • without passing max as argument, is there any way to achieve it?? – rubyist Nov 06 '14 at 11:04
  • THe thing is max arugment is set inside this test_method. So it cannot be hardcoded since We will not know in advance value of max – rubyist Nov 06 '14 at 11:05
  • If you call that method without an argument (`test_method`) then `max` will be `500` like in your example. But if you want to run test will smaller `max` values, you can call the method with an argument (e.g. `test_method(5)`). Beside that: No, you cannot change a local variable that is assigned in a method from a spec. It must be defined outside of the method. – spickermann Nov 06 '14 at 11:18
  • @rubyist *"We will not know in advance value of max"* could you explain that? In your code, `max` is set to `500`. – Stefan Nov 06 '14 at 11:19
  • That is just a pseudo code.. My original code is like this http://stackoverflow.com/questions/26776782/rspec-testing-the-return-value-after-looping – rubyist Nov 06 '14 at 11:21
  • @rubyist you're already stubbing the JSON request, just set a lower value in `sample.json` and your method will use that value. – Stefan Nov 06 '14 at 11:28
  • Yes.. I see that.. Great.. I was not knowing the actual use of stub method. I am just learning Rspec while experimenting.. Thanks a lot – rubyist Nov 06 '14 at 11:34