我在模型中有方法
(用户模型)
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.should匹配(/#{@ user.reset_code} /)----不工作
在一封信中,我给出了带有reset_code的url,如下所示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
这是工作!
谢谢大家,问题已经结束
答案 0 :(得分:4)
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
答案 1 :(得分:2)
你可以使用
mail = ActionMailer::Base.deliveries.last
在规范上调用该方法后获取最后一封电子邮件,然后您可以针对mail.to或mail.body.raw_source
执行规范答案 2 :(得分:1)
这样的事情可以帮助你......我使用了Rspec matchers
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