Search code examples
ruby-on-railsrspecactionmailerinstance-variables

How to test instance variables in an ActionMailer object?


There is a before_action callback method in my ActionMailer object which is responsible for setting some instance variables.

class TestMailer < ApplicationMailer
   before_action :set_params

   def send_test_mail
     mail(to: @email, subject: subject)
   end

   def set_params
     @account = account.email 
     @date = some_action(account.updated_at)
   end
end

The question is How one can test these variables in a rspec test? some thing like:

describe TestMailer do 
 describe '#set_params' do
   described_class.with(account: account, subject: subject).send_test_mail.deliver_now
   expect(@date).to eq(Date.today)
 end
end

any clue would be highly appreciated.


Solution

  • you could setup a spy inside a mock method instance_variable_set, then validate that spy

    class TestMailer < ApplicationMailer
     attr_accessor :day
     # ...
    end
    
    describe TestMailer do 
     let(:freeze_today) { Time.now.utc }
    
     it '#set_params' do 
      # freeze today
      allow_any_instance_of(TestMailer).to receive(:some_action)
      .with(account.updated_at)
      .and_return(freeze_today)
    
      # spy
      @spy = nil
      allow_any_instance_of(TestMailer).to receive(:day=) do |time|
       @spy = time
      end
    
      described_class.with(account: account, subject: subject)
      .send_test_mail
      .deliver_now
    
      expect(@spy).to eq(freeze_today)
    
      # or just simple like this  
      expect_any_instance_of(TestMailer).to receive(:day=).with(freeze_today)
     end
    end