Writing tests for rake tasks
Now, when you are prepared to write the tests, it's time to figure out how to do it. To demonstrate this, assume that we have to write a rake task named send_email
, which has these optional arguments: subject
and body
. The task should write the given strings to a sent_email.txt
file (this is for the purpose of simplicity to demonstrate the tests; in reality, you may want to use a real mailer).
Start to solve the problem statement. The following is a basic class Mailer
that will be used in the rake task (place this code in the mailer.rb
file):
class Mailer DESTINATION = 'sent_email.txt'.freeze DEFAULT_SUBJECT = 'Greeting!' DEFAULT_BODY = 'Hello!' def initialize(options = {}) @subject = options[:subject] || DEFAULT_SUBJECT @body = options[:body] || DEFAULT_BODY end def send puts 'Sending email...' File.open(DESTINATION, 'w') do |f| f << "Subject: #{@subject}\n" f << @body end puts 'Done!' end end
The...