在模型中使用“puts”是否有更好的替代方案?

时间:2013-07-22 12:01:14

标签: ruby-on-rails rspec

我在遗留项目中有一个类,如下所示:

class UserObserver < ActiveRecord::Observer
  def after_create(user)
    unless Rails.env == "development"  # don't spam users when running legacy migrations
      begin
        UserMailer.welcome(user).deliver
        subscribe_user_to_new_account_mailinglist user
      rescue
        # THE FOLLOWING LINE IS THE ONE THAT BOTHERS ME
        puts "User##{user.id} - Signed up using an invalid email address."
      end
    end
  end
end

如你所见,那里有puts。当我运行我们的测试套件时,我得到这样的输出:

be rspec spec/models/user_spec.rb
User#1 - Signed up using an invalid email address.
...User#1 - Signed up using an invalid email address.
..User#1 - Signed up using an invalid email address.
.User#1 - Signed up using an invalid email address.
.User#1 - Signed up using an invalid email address.
.User#1 - Signed up using an invalid email address.
.User#1 - Signed up using an invalid email address.
.User#1 - Signed up using an invalid email address.
.User#1 - Signed up using an invalid email address.
.User#1 - Signed up using an invalid email address.
.User#1 - Signed up using an invalid email address.
.User#1 - Signed up using an invalid email address.
.User#1 - Signed up using an invalid email address.
.User#1 - Signed up using an invalid email address.
.User#1 - Signed up using an invalid email address.
.

Finished in 12.19 seconds
18 examples, 0 failures

我不是那种杂乱无章的粉丝。好像我应该只看到绿点。

在该行而不是puts上做什么更好?

1 个答案:

答案 0 :(得分:0)

在救援中你可以使用: -

flash[:error] = error.message "User##{user.id} - Signed up using an invalid email address." 

这也将使测试成为绿色。