是否可以在非模拟对象上调用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/