使用 rspec 测试 after_create 挂钩
我的模型(RoR 3.0.x)中的代码或多或少像这样:
class Message
after_create :notify
protected
def notify
if visible?
Notifier.message_from_portfolio( user, self ).deliver
else
Notifier.invisible_message_from_portfolio( user, self ).deliver
end
end
end
并且我正在使用最新的 rspec gem 来测试它。 问题是我无法测试通知方法:如果我直接测试它,我不能,因为它是受保护的,如果我创建一条消息并设置期望,它就不起作用,因为显然即使 rspec 运行通知方法我无法及时接听电话。
我的规范是:
describe :notification do
it "should send the whole message by email when visible" do
u = Factory.create( :user, :account_type => 1 )
message = u.messages.build( :body => "Whatever", :author => "Nobody", :email => "[email protected]" )
Notifier.should_receive( :message_from_portfolio )
message.save
end
end
对象通知程序从不接收 message_from_portfolio。我做错了什么?建议?
I have code in my model (RoR 3.0.x) that is more or less like this:
class Message
after_create :notify
protected
def notify
if visible?
Notifier.message_from_portfolio( user, self ).deliver
else
Notifier.invisible_message_from_portfolio( user, self ).deliver
end
end
end
And I'm using the latest rspec gem to test it.
The problem is that I'm not able to test the notify method: if I test it directly I can't because it's protected, if I create a message and set expectations it doesn't work because apparently even though rspec runs the notify metod I'm not able to catch the calls in time.
My spec is:
describe :notification do
it "should send the whole message by email when visible" do
u = Factory.create( :user, :account_type => 1 )
message = u.messages.build( :body => "Whatever", :author => "Nobody", :email => "[email protected]" )
Notifier.should_receive( :message_from_portfolio )
message.save
end
end
The object Notifier never receives message_from_portfolio. What am I doing wrong? Suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Factory.create
已经保存了消息,所以它没有被创建,只是保存。将其替换为 Factory.build ,一切都应该没问题。Factory.create
has already saved message, so it is not being created, just saved. Substitute it withFactory.build
and all should be fine.您确定回调已到达吗?如果实例无效,则
after_create
不会执行。您可以设置一个用于调试目的的期望:
或者
visible?
返回 false?要检查这一点,您可以使用负期望:Are you sure the callback is being reached?
after_create
doesn't get executed if the instance is invalid.You could set an expectation for debugging purposes:
Or maybe
visible?
returns false? To check for that you could use a negative expectation: