Robert Feldt
11/1/2006 5:51:00 AM
Hi,
I'm playing around with BDD à la test/spec and foudn that I need to
specify properties probabilistically ie saying that they are
likely/unlikely. Has there been any previous work along these lines?
Should we add something like this to test/spec (Christian are you listening? :))
diff -rN old-testspec/lib/test/spec.rb new-testspec/lib/test/spec.rb
286a287,300
> def unlikely(specname, probability = 0.01, preName = "unlikely", &block)
> specify(preName + " " + specname) do
> count = 0
> num_repetitions = 100
> num_repetitions.times {count += 1 if (block.call == true)}
> actual_probability = count.to_f / num_repetitions
> assert actual_probability <= probability, "Expected probability of #{probability} but was #{actual_probability} (#{count} in #{num_repetitions} repetitions)"
> end
> end
>
> def likely(specname, probability = 0.99, &block)
> unlikely(specname, 1.0 - probability, "likely") {!block.call}
> end
>
so that one can write specs like
> # Example of probabilistic specifications
>
> context "random generation" do
> unlikely "that two consecutive calls to rand gives the same value" do
> rand(1000) == rand(1000)
> end
>
> likely "that two consecutive calls to rand gives different values" do
> rand(1000) != rand(1000)
> end
> end
?
This should probably be generalized so that the number of repetitions
to run depends on the probability of the event but I think you get the
idea.
Comments?
/Robert Feldt