是否可以在非模拟对象上调用should_receive
?
如果是的话,我想知道为什么这个测试没有通过。 SiteStyle
has_many images
当我在site_style上致电duplicate!
时,我希望images
也可以自己致电duplicate
。测试失败。实际的图像虽然重复了。那是为什么?
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
SiteStyleSpec:
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
答案 0 :(得分:4)
你的话在这里:
@image.should_receive(:duplicate!).once
仅使用该特定的@image实例,并仅在其上调用should_receive,以便期望不会转移到复制方法(或实例化图像的任何其他位置)内使用的图像对象,即使它是来自数据库的相同记录。