Manasi Salvi

RSpec mocks

Writing tests is important (yes, we all know that) and it’s taken me a couple of years to get familiar with writing tests with RSpec. Learning to write method stubs, fakes, working with test doubles and working around caveats - big and small. For example: not every class is required to test what the usecases or classes within it return. It might be sufficient in these scenarios to get away with rspec-mocks, RSpec’s test double-framework. While first learning about RSpec I often got stuck with the test setup using mocks. There’s a plethora of blogs and Stack Overflow posts about this, these are just some that I didn’t come across as easily and the ones I use repeatedly in testing.

  Class Apple
    loop do
      x = Foo.something
    end

    break unless Bar.find_by(x: x)
  end

  let(:foo) { Foo.new }

  before do
    foo.stub(:something) do
      foo.unstub(:something) do
    end
  end
  Class GoodApple
    def foo
      # use_case returns value of do_something
      use_case = Apple.knife
      ...
    end
  end

  let(:use_case_double) do
    instance_double(Apple, do_something: did_something)
  end

  before do
    allow(Apple).to_receive(:knife).and_return(use_case_double)
  end
  Class GoodApple
    def foo
      use_case = Apple.knife(plate: funky_plate)
      ...
    end
  end

  let(:plate) { create(:plate) }
  let(:use_case_double) do
    instance_double(Apple, do_something: did_something)
  end

  before do
    allow(Apple).to_receive(:knife).with(plate: plate).and_return(use_case_double)
  end
  Class GoodApple
    def foo
      use_case = Apple.knife(plate: funky_plate)
      return use_case.core.seed
    end
  end

  let(:plate) { create(:plate) }
  let(:use_case_double) do
    instance_double(Apple, core: core_double)
  end
  let(:core_double) do
    instance_double(CoreClass, seed: '123')
  end

  before do
    allow(Apple).to_receive(:knife).with(plate: plate).and_return(use_case_double)
  end
  let(:use_case_double) do
    OpenStruct.new(core: core_double)
  end

comments powered by Disqus