[英]Can not test mailer action called in rspec rails
In mailer of rails, as I know all method will be class method. 我知道在Rails的邮件中,所有方法都是类方法。 But I can not test my mailer method called:
但是我无法测试我的邮件方法:
user_mailer_spec.rb: user_mailer_spec.rb:
it "should call send_notifition method" do
@user = FactoryGirl.build(:user)
notify_email = double(:send_notifition)
expect(UsersMailer.new).to receive(:notify_email).with(@user)
@user.save
end
user_mailer.rb: user_mailer.rb:
def notify(user)
mail to: user.email, subject: "Example"
end
user.rb: user.rb:
after_commit :send_notifition
private
def send_notifition
UsersMailer.notify(self)
end
The above codes will not pass but when I change notifition to self.notifition, it pass: 上面的代码不会通过,但是当我将通知更改为self.notifition时,它会通过:
def self.notify(user)
mail to: user.email, subject: "Example"
end
First of all, I'd like to point you to an awesome gem for testing emails: https://github.com/email-spec/email-spec . 首先,我想向您指出一个很棒的宝石来测试电子邮件: https : //github.com/email-spec/email-spec 。
I think the problem is that you're asserting on UsersMailer.new
, thus putting a mock on a different instance than the one then being instantiated by the User
model. 我认为问题在于您是在
UsersMailer.new
上UsersMailer.new
,因此将模拟放在不同于实例的另一实例上,然后由User
模型实例化该实例。 I generally test emails like this without any issues: 我通常会像这样测试电子邮件,没有任何问题:
it "should call send_notifition method" do
@user = FactoryGirl.build(:user)
mail = double(:mail)
expect(UsersMailer).to receive(:notify_email).with(@user).and_return(mail)
expect(mail).to receive(:deliver_later) # or deliver_now, if you don't use a background queue
@user.save
end
Note how I'm doing expect(UsersMailer)
instead of expect(UsersMailer.new)
and also take not that I'm asserting that the email is actually delivered (I think a deliver statement is missing in your code). 请注意,我是如何执行
expect(UsersMailer)
而不是expect(UsersMailer)
expect(UsersMailer.new)
,还请注意,我不是在断言电子邮件实际上已传递(我认为您的代码中缺少传递语句)。
Hope that helps. 希望能有所帮助。
Solved: Thank you @Clemens Kofler for supporting. 解决:谢谢@Clemens Kofler的支持。 I have many mistaking in my code:
我的代码有很多误解:
from 从
after_commit :send_notifition
private
def send_notifition
UsersMailer.notify(self)
end
to 至
after_commit :send_notifition
private
def send_notifition
UsersMailer.notify(self).deliver
end
from 从
it "should call send_notifition method" do
@user = FactoryGirl.build(:user)
expect(@user).to receive(:send_notifition)
notify_email = double(:send_notifition)
expect(UsersMailer.new).to receive(:notify_email).with(@user)
@user.save
end
to 至
it "should call send_notifition_mail_if_created_new_hospital method" do
@user = FactoryGirl.build(:user)
# I don't know why "expect(@user).to receive(:send_notifition)" not passed here
mail = double(:mail)
expect(UsersMailer).to receive(:notify_email).with(@user).and_return(mail)
allow(mail).to receive(:deliver)
@user.save
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.