ruby-on-rails - Rspec 如何为重写的方法设置对父类(super class)的期望

标签 ruby-on-rails activerecord rspec

我有一个覆盖 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/

相关文章:

ruby-on-rails - 如何判断哪个关联模型未通过ActiveRecord验证?

ruby - 在 Selenium 2.9 中选择图像

ruby-on-rails - 使用 RoR 停止在 Heroku 上看到 SQL 级别的日志

ruby-on-rails - Heroku:rails:获取 "No such file to load -- URI (LoadError)"

ruby-on-rails - 正确关联 Ruby on Rails

ruby-on-rails-3 - 如何 stub 部分 session 以模拟授权 session ?

ruby-on-rails - 工厂女孩: can one reopen factory definitions and complete them?

ruby-on-rails - 使用Rails 3(在Heroku上)进行 Assets 管理(Jammit,AssetHat,Rack PageSpeed)

ruby-on-rails - 如何使用 Rails Cucumber、rspec、capybara 在 View (dhtml) 中测试动态部件?

ruby-on-rails - activerecord has_many :through find with one sql call