我有這個類:如何正確使用模擬?
class EnablePost
def initialize(post_klass, id)
raise "oops" if post_klass.blank?
@post_klass = post_klass
@id = id
end
def perform
post = @post_klass.find_by_id(@id)
return unless post
post.update_attribute :enabled, true
end
end
我必須寫規範檢驗以上:
describe EnablePost do
it "should enable a post" do
post = mock
post.should_receive(:blank?).and_return(false)
post.should_receive(:find_by_id).with(22).and_return(post)
post.should_receive(:update_attribute).with(:enabled, true)
result = EnablePost.new(Post, 22).perform
result.should be_true
end
end
但我真正想要做的是把EnablePost
作爲一個黑盒子。我不想模擬:blank?
,:find_by_id
或:update_attribute
。 也就是說我想我的規格看起來像:
describe EnablePost do
it "should enable a post" do
post = mock
result = EnablePost.new(post, 22).perform
result.should be_true
end
end
缺少什麼我在這裏?我使用錯誤嗎?
還檢查了http://martinfowler.com/articles/mocksArentStubs.html – Zombies 2013-02-09 09:18:52