0

In some tests I'm writing I need to create a lot of stubs that are pretty similar. I'm using Mocha.

user.stubs(:hq?).returns(false)
user.stubs(:has_role?).with("admin").returns(true)

And so on. It's a combinatorial thing that's very repetitive and un-dry. I'm wondering if I could switch this to some sort of chainable dsl.

user = user_stubber.hq.with_role("admin")

Is there a good way to approach this in Mocha. Or is there a better stubbing library that would give me this ability?

Hopwise
  • 293
  • 2
  • 11

1 Answers1

0

My eventual solution was this user_stubber.rb file that I put in /test/lib/.

require 'mocha'

class UserStubber

  def no_roles
    self.stubs(has_role?: false)
    self
  end

  def hq
    self.stubs(:hq?).returns(true)
    self
  end 

  def field
    self.stubs(:hq?).returns(false)
    self
  end

  def with_role(role)
    self.stubs(:has_role?).with(role).returns(true)
    self
  end
end

In the tests I can now do:

user.no_roles.hq.with_role('admin')

And so on. And since it returns a stubbable object, I can do

user.hq.stubs(:other_method).with(params).returns(true)
Hopwise
  • 293
  • 2
  • 11