2

我在模型中有方法

(用户模型)

  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:用谷歌,但没有找到例子

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 match(/#{@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 

这是工作!

谢谢大家,问题已结束

4

3 回答 3

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 
于 2012-06-20T16:11:25.217 回答
2

您可以使用

mail = ActionMailer::Base.deliveries.last

要获取在规范上调用该方法后发送的最后一封电子邮件,那么您可以针对 mail.to 或 mail.body.raw_source 进行规范

于 2012-06-19T19:13:49.097 回答
1

像这样的东西应该可以帮助你..我用过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
于 2012-06-19T18:26:43.910 回答