Nice pattern for creating a new class in your rspec tests

Updated . Posted . Visible to the public.

Instead of defining a regular class, which would then be available to all tests, you can create a class within a let block like this:

let(:my_object) do
  my_class = Class.new(MyClass) do
    def do_stuff(data)
      # ...
    end
  end

  my_class.new
end

If you need more than one instance, you can of course also return the class and use it for multiple records:

let(:my_class) do
  Class.new(MyClass) do
    def do_stuff(data)
      # ...
    end
  end
end

let(:first_object) { myclass.new }
let(:second_object) { myclass.new }
Judith Roth
Last edit
Judith Roth
Posted by Judith Roth to Judith's Dev Notes (2021-05-26 14:18)