Serge Vinogradoff
Serge Vinogradoff

Reputation: 2272

How to test random events in Rails?

I've encountered an interesting task.

Need to make a method that would randomly (in 10-15% cases) modify a string in a certain way.

How do I do that with TDD?

E.g. how to make sure that probability of modification will be not more than 15%?

Thx.

Upvotes: 0

Views: 162

Answers (2)

iltempo
iltempo

Reputation: 16012

If you are asking how to test: Run your method 100 times (for example) and assert that the string didn't change more than 15 times.

Upvotes: 1

bvogelzang
bvogelzang

Reputation: 1415

Just use random number generation:

def change_string_fifteen_percent_of_the_time
    if rand() <= 0.15
        # change string here
    end
end

Upvotes: 2

Related Questions