Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the benefit of Class.new in this Rspec

I am reading through some Rspec written by someone who left the company. I am wondering about this line:

  let(:mailer_class) { Class.new(AxeMailer) }
  let(:mailer) { mailer_class.new }

  describe '#check' do
    before do
      mailer_class.username 'username'
      mailer.from '[email protected]'
      mailer.subject 'subject'
    end
    subject { lambda { mailer.send(:check) } }

It is testing this class:

class AxeMailer < AbstractController::Base

  def self.controller_path
    @controller_path ||= name.sub(/Mailer$/, '').underscore
  end

I want to know the difference between this and let(:mailer_class) { AxeMailer }.

I ask this because currently when I run the test, it will complain name is nil. But if I changed it, it will test fine.

I think this issue started after using Rails 3.2, and I think name is inherited from AbstractController::Base.

This is the same in the console (meaning it is not Rspec specific), I can do AxeMailer.name with no error, but if I do Class.new(AxeMailer) there is is the problem.

My questions are:

  1. Is there a reason to use Class.new(AxeMailer) over AxeMailer
  2. Is there a problem if I just change this?
  3. Is there a way not change the spec and make it pass?
like image 928
lulalala Avatar asked Nov 05 '22 03:11

lulalala


1 Answers

I'm guessing it was written this was because of the mailer_class.username 'username' line. If you just used AxeMailer directly, the username setting would be carried over between tests. By creating a new subclass for each test, you can make sure that no state is carried over between them.

like image 66
Emily Avatar answered Nov 10 '22 16:11

Emily