【问题标题】:Rspec how to set an expectation on the superclass for an overridden methodRspec如何为重写方法设置超类的期望
【发布时间】:2011-11-16 17:55:55
【问题描述】:

我有一个覆盖 update_attributes 的模型类:

class Foo < ActiveRecord::Base
  def update_attributes(attributes)
    if super(attributes)
      #do some other cool stuff
    end
  end
end

我试图弄清楚如何在 update_attributes 的超级版本上设置期望和/或存根,以确保在成功的情况下完成其他工作。另外我想确保超级方法实际上被调用了。

这是我迄今为止尝试过的(当然没有成功):

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

有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails activerecord rspec


    【解决方案1】:

    update_attributes 是一个实例方法,而不是类方法,所以据我所知,您不能使用 rspec-mocks 直接在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
    

    【讨论】:

      【解决方案2】:

      尝试将should_recieve 替换为should_receive

      【讨论】:

      • 哈!是的,那会有所帮助。接得好。 I 在 E 之前,除了在 C. Sheesh 之后。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-23
      • 1970-01-01
      相关资源
      最近更新 更多