每天一剂Rails良药之Testing Incoming Email

今天来看看Rails对接收Email的测试,首先[b]ruby script/generate mailer Receiver[/b],Rails会自动为我们生成test/unit/receiver_test_pristine.rb:
[code]
require File.dirname(__FILE__) + '/../test_helper'
require 'receiver'

class ReceiverTest < Test::Unit::TestCase
FIXTURES_PATH = File.dirname(__FILE__) + '/../fixtures'
CHARSET = 'utf-8"

include ActionMailer::Quoting

def setup
ActionMailer::Base.delivery_method = :test
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.deliveries = []

@expected = TMail::Mail.new
@expected.set_content_type "text", "plain", { "charset" => CHARSET }
end

private
def read_fixture(action)
IO.readlines("#{FIXTURES_PATH/receiver/#{action}")
end

def encode(subject)
quoted_printable(subject, CHARSET)
end
end
[/code]
这样可以在test/fixtures/receiver目录下保存一些Email的源文件作为数据,例如下面将用到的文件有
test/fixtures/receiver/confidential_opportunity和test/fixtures/receiver/latest_screensaver这两个文件
我们可以使用[url=http://www.mozilla.com]Thunderbird[/url]来查看Message Source
下面定义我们的receiver:
app/modles/receiver.rb
[code]
class Receiver < ActionMailer::Base

def receive(email)

rating = 0

if(email.subject + email.body =~ /opportunity/i)
rating += 1
end

if email.has_attachments?
email.attachments.each do |attachment|
rating += 1 if attachment.original_filename =~ /zip$/i
end
end

Mail.create(:subject => email.subject,
:body => email.body,
:sender => email.form,
rating => rating)
end
end
[/code]
下面来写我们自己的test/unit/receiver_test.rb:
[code]
def test_fixtures_are_working
emial_text = read_fixture("confidential_opportunity").join
assert_match(/opportunity/i, email_text)
end

def test_incoming_email_gets_added_to_database
count_before = Mail.count
email_text = read_fixture("confidential_opportunity").join
Receiver.receive(email_text)
assert_equal(count_before + 1, Mail.count)
assert_equal("CONFIDENTIAL OPPORTUNITY", Mail.find(:all).last.subject)
end

def test_email_containing_opportunity_rates_higher
email-text = read_fixture("confidential_opportunity").join
Receiver.receive(email_text)
assert(Mail.find_by_subject("CONFIDENTIAL OPPORTUNITY").rating > 0)
end

def test_zip_file_increases_rating
email_text = read_fixture("latest_screensaver").join
Receiver.receive(email_text)
assert(Mail.find_by_subject("The latest new screensaver!").rating > 0)
end
[/code]
上面我们测试了接收Email以及接收带附件的Email,注意附件会编码为文本来传输,通过查看Email的源文本可以看到
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值