如何测试 ActionMailer 对象中的实例变量?
How to test instance variables in an ActionMailer object?
在我的 ActionMailer 对象中有一个 before_action
回调方法,它负责设置一些实例变量。
class TestMailer < ApplicationMailer
before_action :set_params
def send_test_mail
mail(to: @email, subject: subject)
end
def set_params
@account = account.email
@date = some_action(account.updated_at)
end
end
问题是如何在 rspec 测试中测试这些变量?
像这样的东西:
describe TestMailer do
describe '#set_params' do
described_class.with(account: account, subject: subject).send_test_mail.deliver_now
expect(@date).to eq(Date.today)
end
end
任何线索将不胜感激。
您可以在模拟方法 instance_variable_set
中设置一个 spy
,然后验证该间谍
class TestMailer < ApplicationMailer
attr_accessor :day
# ...
end
describe TestMailer do
let(:freeze_today) { Time.now.utc }
it '#set_params' do
# freeze today
allow_any_instance_of(TestMailer).to receive(:some_action)
.with(account.updated_at)
.and_return(freeze_today)
# spy
@spy = nil
allow_any_instance_of(TestMailer).to receive(:day=) do |time|
@spy = time
end
described_class.with(account: account, subject: subject)
.send_test_mail
.deliver_now
expect(@spy).to eq(freeze_today)
# or just simple like this
expect_any_instance_of(TestMailer).to receive(:day=).with(freeze_today)
end
end
我认为与其测试实例变量,还不如测试邮件正文,例如:
expect(mail.body.encoded).to include(account.updated_at)
在我的 ActionMailer 对象中有一个 before_action
回调方法,它负责设置一些实例变量。
class TestMailer < ApplicationMailer
before_action :set_params
def send_test_mail
mail(to: @email, subject: subject)
end
def set_params
@account = account.email
@date = some_action(account.updated_at)
end
end
问题是如何在 rspec 测试中测试这些变量? 像这样的东西:
describe TestMailer do
describe '#set_params' do
described_class.with(account: account, subject: subject).send_test_mail.deliver_now
expect(@date).to eq(Date.today)
end
end
任何线索将不胜感激。
您可以在模拟方法 instance_variable_set
中设置一个 spy
,然后验证该间谍
class TestMailer < ApplicationMailer
attr_accessor :day
# ...
end
describe TestMailer do
let(:freeze_today) { Time.now.utc }
it '#set_params' do
# freeze today
allow_any_instance_of(TestMailer).to receive(:some_action)
.with(account.updated_at)
.and_return(freeze_today)
# spy
@spy = nil
allow_any_instance_of(TestMailer).to receive(:day=) do |time|
@spy = time
end
described_class.with(account: account, subject: subject)
.send_test_mail
.deliver_now
expect(@spy).to eq(freeze_today)
# or just simple like this
expect_any_instance_of(TestMailer).to receive(:day=).with(freeze_today)
end
end
我认为与其测试实例变量,还不如测试邮件正文,例如:
expect(mail.body.encoded).to include(account.updated_at)