Bungus Bungus - 3 months ago 14
Ruby Question

Is there an idiomatic way to dry up repeated method calls in RSpec

When the same call is made repeatedly in the same describe block e.g.

RSpec.describe Grant do
let(:grant) { Grant.make }

describe "#exchange!" do
it "destroys token" do
grant.exchange! # dry me up!
expect(grant).to be_destroyed
end
it "returns a Token" do
expect(grant.exchange!).to be_a(Token) # dry me up!
end
end
end


I want to dry up
grant.exchange!


I've worked out how to do it with
subject
, but I know explicit subjects are smelly.

Answer

You could use let! to define a memoized helper that is executed before each example:

RSpec.describe Grant do
  let(:grant) { Grant.make }

  describe "#exchange!" do
    let!(:result) { grant.exchange! }

    it "destroys token" do
      expect(grant).to be_destroyed
    end

    it "returns a Token" do
      expect(result).to be_a(Token)
    end
  end
end

However, I personally prefer to call the method explicitly from within the example, just like in your code. It makes it easier to deal with the state before and after the invocation.

Comments