I was not aware this was possible until I came across this post looking for examples of using ActiveRecord and rspec in unison.
I frequently make use of sample data in my posts; most commonly in the form of arrays.
In the midst of "shooting the breeze" with my fellow companions on the awesome "programmer files" gist, I could have made use of:
Array.new(3) { Person.new }
That's a pretty convenient bit of syntax to call upon moving forward. It's essentially writing the loop for you underneath the covers; repeatedly invoking the block. I'm willing to bet you I could reverse engineer this guy too; let me take a stab at it.
Before I hack on this sample, I'll fill you in on my thought process. Declaratively speaking, "Invoke this block n number of times."
That's essentially the specification we want to adhere to. "Let's dance, shall we?".
require 'rspec/autorun'
module Kernel
def AntwanArray(count, &block)
end
end
describe 'AntwanArray' do
let(:count) { 3 }
it 'should create an array with the number of elements equal to count' do
expect(AntwanArray(count) { Array(5) } ).to eq Array.new(count) { Array(5) }
end
end
And upon running our spec, we get:
Failures:
1) AntwanArray should create an array with the number of elements equal to count
Failure/Error: Unable to find matching line from backtrace
expected: [[5], [5], [5]]
got: nil
(compared using ==)
# array-conversion.rb:15:in `block (2 levels) in <main>'
Finished in 0.00137 seconds
1 example, 1 failure
Failed examples:
rspec array-conversion.rb:12 # AntwanArray should create an array with the number of
elements equal to count
shell returned 1
"It's time to pass the test"
module Kernel
def AntwanArray(count, &block)
result = []
count.times { result << yield }
result
end
end
Finished in 0.00162 seconds
1 example, 0 failures
Press ENTER or type command to continue
"All green now"