I just read this article titled Useful RSpec trick for testing method with arguments which shows a nifty way to write a repetitive test-suite where you want to verify different arguments give the correct/expected result.
The method proposed by the author looks like this:
RSpec.describe Daru::Index do
let(:index) { described_class.new [:a, :b, :c, :d] }
describe '#pos' do
subject { index.method(:pos) }
context 'by label' do
its([:a]) { is_expected.to eq 0 }
its([:a, :c]) { is_expected.to eq [0, 2] }
its([:b..:d]) { is_expected.to eq [1, 2, 3] }
# .. and so on
Which is looking very readable and compact! This solution makes a lot of use of subject, let
and relies on its
to make it work. Then the author proceeds to list a few more basic/default rspec ways but does not list how I in general write tests like that.
Not sure if it is more readable or not, but imho it is in general a lot less work, it is usable for a all kinds of repetitive tests.
Let's see how it looks:
RSpec.describe Daru::Index do
let(:index) { described_class.new [:a, :b, :c, :d] }
describe '#pos' do
context 'by label' do
[[[:a], 0],
[[:a, :c], [0,2] ],
[[:b ..:d], [1,2,3] ],
# and so on
].each do |arr|
it "returns #{arr[1].inspect} for #{arr[0].inspect}" do
expect(index.pos(arr[0]).to eq(arr[1])
end
end
end
end
end
(note: not actually sure if this code works, but you get the gist of it I hope)
So I use ruby meta-programming to define a whole test-suite when the file is loaded, and when I need to test another input-output, I can just add it to the list, no need to copy-paste.
Comments
Add comment