[英]RSpec test model and mailer
我在模型中有方法
(用戶模型)
def create_reset_code
self.attributes = {:reset_code => Digest::SHA1.hexdigest( Time.now.to_s.split(//).sort_by {rand}.join )}
save(:validate=>false)
UserMailer.reset_password_email(self).deliver
end
如何在RSpec中對其進行測試? 我想測試代碼生成,並發送電子郵件
PS:使用Google,但未找到任何示例
UPD
我寫了兩個測試:
it "should create reset code" do
@user.create_reset_code
@user.reset_code.should_not be_nil
end
it "should send reset code by email" do
@user.create_reset_code
@email_confirmation = ActionMailer::Base.deliveries.first
@email_confirmation.to.should == [@user.email]
@email_confirmation.subject.should == I18n.t('emailer.pass_reset.subject')
@email_confirmation.body.should match(/#{@user.reset_code}/)
end
但這--- @ email_confirmation.body。應該匹配(/#{@user.reset_code}/)----不起作用
在一封信中,我給網址加上reset_code,如下所示reset_password_url(@ user.reset_code)
固定
it "should send reset code by email" do
@user.create_reset_code
@email_confirmation = ActionMailer::Base.deliveries.last
@email_confirmation.to.should == [@user.email]
@email_confirmation.subject.should == I18n.t('emailer.pass_reset.subject')
@email_confirmation.html_part.body.should match /#{@user.reset_code}/
end
是工作!
謝謝大家,問題已經解決
it "should create reset code" do
@user.create_reset_code
@user.reset_code.should_not be_nil
end
it "should send reset code by email" do
@user.create_reset_code
@email_confirmation = ActionMailer::Base.deliveries.last
@email_confirmation.to.should == [@user.email]
@email_confirmation.subject.should == I18n.t('emailer.pass_reset.subject')
@email_confirmation.html_part.body.should match /#{@user.reset_code}/
end
您可以使用
mail = ActionMailer::Base.deliveries.last
要獲取在規范上調用該方法后發送的最后一封電子郵件,則可以針對mail.to或mail.body.raw_source進行規范
這樣的東西應該對您有幫助。.我已經使用過Rspec匹配器
it "should test your functionality" do
user = Factory(:ur_table, :name => 'xyz', :email => 'xyz@gmail.com')
obj = Factory(:ur_model_table)
key = Digest::SHA1.hexdigest( Time.now.to_s.split(//).sort_by {rand}.join
data = obj.create_reset_code
data.reset_code.should be(key)
let(:mail) {UserMailer.reset_password_email(user) }
mail.to.should be(user.email)
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.