我有一个覆盖 update_attributes 的模型类:
class Foo < ActiveRecord::Base
def update_attributes(attributes)
if super(attributes)
#do some other cool stuff
end
end
end
我正在尝试弄清楚如何在 update_attributes 的 super 版本上设置期望和/或 stub ,以确保在成功的情况下完成其他事情。此外,我想确保真正调用了 super 方法。
这是我到目前为止尝试过的方法(当然没有成功):
describe "#update_attributes override" do
it "calls the base class version" do
parameters = Factory.attributes_for(:foo)
foo = Factory(:foo, :title => "old title")
ActiveRecord::Base.should_receive(:update_attributes).once
foo.update_attributes(parameters)
end
end
这当然行不通:
Failure/Error: ActiveRecord::Base.should_recieve(:update_attributes).once
NoMethodError:
undefined method `should_recieve' for ActiveRecord::Base:Class
有什么想法吗?
最佳答案
update_attributes
是实例方法,而不是类方法,因此据我所知,您不能使用 rspec-mocks 将其直接 stub 在 ActiveRecord::Base
上。而且我认为您不应该这样做:super
的使用是您不应该将测试耦合到的实现细节。相反,最好编写示例来指定您想要实现的行为。如果不使用 super
,您会从使用 super
得到什么行为?
举个例子,如果这是代码:
class Foo < ActiveRecord::Base
def update_attributes(attributes)
if super(attributes)
MyMailer.deliver_notification_email
end
end
end
...那么我认为有趣的相关行为是只有在没有验证错误的情况下才会发送电子邮件(因为这将导致 super
返回 true 而不是 false)。所以,我可能会像这样说明这种行为:
describe Foo do
describe "#update_attributes" do
it 'sends an email when it passes validations' do
record = Foo.new
record.stub(:valid? => true)
MyMailer.should_receive(:deliver_notification_email)
record.update_attributes(:some => 'attribute')
end
it 'does not sent an email when it fails validations' do
record = Foo.new
record.stub(:valid? => false)
MyMailer.should_receive(:deliver_notification_email)
record.update_attributes(:some => 'attribute')
end
end
end
关于ruby-on-rails - Rspec 如何为重写的方法设置对父类(super class)的期望,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8156344/