0

I am new to Rspec, i am trying to write a test for a simple feature.

A user creates a contract, if the contract the is created and has a specific value on its property then i send an email to notify the teacher. How do i write the condition in the test?

I am using letter_opener and ActionMailer.

describe "When a user creates a apprentice contract" do
 let(:admin) { users(:admin) }
 before { signin admin }

  it "should send an email to the teacher" do
    contract = create(:contract)
    contract.education_type.must_equal("company_apprentice")  
  end
end

when contract.education_type.must_equal("school_apprentice") is true i want to test if it sends an email.

How do i write that in this test?

Webbie
  • 537
  • 2
  • 10
  • 25

1 Answers1

1
it 'should send an email to the teacher' do
  expect { create(:contract, education_type: 'company_apprentice' }
    .to change { ActionMailer::Base.deliveries.count }
    .by(1)
end

you also need this set:

# config/environments/test.rb
config.action_mailer.delivery_method = :test
Hubert Jakubiak
  • 853
  • 8
  • 19
  • Im getting an error ```NoMethodError: undefined method `change' ``` – Webbie Jul 13 '19 at 22:23
  • im using the ```minitest-spec-rails``` – Webbie Jul 13 '19 at 22:36
  • You do something like here: https://stackoverflow.com/a/17223583/5841310 or at least check if `ActionMailer::Base.deliveries.size` is equal to 1. – Hubert Jakubiak Jul 14 '19 at 20:30
  • minitest-spec-rails is not the same thing at all as rspec. minitest is a completely different test framework. minitest-spec lets you write "BDD" style tests for minitest. – max Jul 14 '19 at 21:47
  • If you are using minitest and rails you can use [`assert_changes` or `assert_difference`](https://api.rubyonrails.org/v5.1.6/classes/ActiveSupport/Testing/Assertions.html) to replicate `expect {}.to change` from RSpec. If you want to learn BDD style testing I would go with RSpec though as its a tight well tested and well documented kit whereas doing BDD with minitest is like a plastic bag filled with odd parts. – max Jul 14 '19 at 21:52