rspec 的 should_receive 在非模拟对象上?

标签 rspec

是否可以在非模拟对象上调用should_receive

如果是的话,我想知道为什么这个测试没有通过。 SiteStyle has_many images 并且当我在 site_style 上调用 duplicate! 时,我希望 images 调用 自身也重复。测试失败。但实际图像会被复制。这是为什么?

SiteStyle 模型:

class SiteStyle < ActiveRecord::Base
  belongs_to :site
  belongs_to :user
  validates_presence_of :name, :user
  has_many :images, :as => :imageable, :order => "position", :dependent => :destroy

  ...

  def duplicate!(user, *args)
    options = args.extract_options!
    to_site ||= Site.find(options[:site_id])
    dup_style = self.class.create :site_id => to_site.id, :name => name, :user_id => user.id
    self.images.each { |image| image.duplicate!(dup_style) }
    dup_style
  end

  ...
end

网站样式规范:

require 'spec_helper'

describe SiteStyle do
  ...

  describe "duplicate!(user, *args)" do
    before do
      @creator = User.make
      @site = Site.make
      @style = SiteStyle.make :site => @site, :user => @creator
    end

    ...

    it "should have a duplicate of the images" do
      @image = Image.make :imageable_type => @style.class.name, :imageable_id => @style.id
      @image.should_receive(:duplicate!).once
      @dup_style = @style.duplicate!(@creator)
    end
  end
end

错误:

Failures:
  ...

  2) SiteStyle duplicate!(user, *args) should have a duplicate of the images
     Failure/Error: @image.should_receive(:duplicate!).once
     (#<Image:0xc7b40d8>).duplicate!(any args)
         expected: 1 time
         received: 0 times
     # ./spec/models/site_style_spec.rb:83

最佳答案

您的线路:

@image.should_receive(:duplicate!).once

仅使用特定的@image实例,并仅对其调用should_receive,以便期望不会转移到重复方法(或实例化图像的任何其他位置)内使用的图像对象,即使它与数据库中的记录相同。

关于rspec 的 should_receive 在非模拟对象上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5074922/

相关文章:

ruby - rspec 检查一个方法是否调用另一个方法

ruby-on-rails - 使用 rswag 关注 JSON Api

ruby-on-rails - sublime text ruby​​ 测试窗口找不到路径

ruby-on-rails - 尝试使用 rspec 和 Capybara 测试 omniauth,失败

ruby-on-rails - RSpec:带参数的 stub 链?

ruby - Rspec:应该是(这个或那个)

ruby-on-rails - 关系的未定义方法 `find_or_initialize'

ruby - simplecov 报告覆盖 0.0%

ruby-on-rails - Capybara/Rspec - 有没有办法在单击提交之前测试输入框是否已填充?

ruby-on-rails - 如何使用 FactoryGirl 发送参数(而不是手动将参数作为散列发送)?