2010-04-20 78 views

回答

15

您可以设置一个message expectation

it "should touch the discussion" do 
    post = Factory.build(:post) 
    post.discussion.should_receive(:touch) 
    post.save! 
end 

下面的例子使用Factory Girl,但你可以使用固定装置或嘲笑为好。

+0

它总是令我感到惊讶Ruby/Rails/Rspec是多么简单优雅。 – 2010-04-21 08:08:33

+2

这真的不是一个'好'的解决方案1)它很慢,因为你正在触及数据库,2)你没有测试触摸是否是after_save回调的一部分,它可能会被任何一个验证或作为保存AR记录的一部分发生的回调。 – Intentss 2014-08-20 21:28:30

+0

@Intentss同意。什么是更好的方法? – 2014-12-10 23:10:33

1

您可以模拟#touch调用,或者验证回调对其的影响。

it "should touch the discussion" do 
    original_updated_at = @discussion.updated_at 
    @post.save! 
    @post.discussion.updated_at.should_not_be == original_updated_at 
end 
9

首先

如果你正在试图做的是断言,touch: true选项设置上的关联性,所有那么你可以做到以下几点:

describe Post do 
    it { should belong_to(:discussion).touch(true) } 
end 

其次

对于一般测试回调,请继续阅读。

所有其他的答案在这里有两个缺陷:

  1. 他们需要的数据库,这可能会很慢上一炮打响。

  2. 他们并不确定回调期间save!

而是调用,使用Shoulda Callback Matchers,这并不需要一个数据库打击,您可以指定哪些回调你测试的存在。

安装

安装Shoulda Callback Matchers与捆扎机:

group :test do 
    gem "shoulda-callback-matchers", "~> 1.0" 
end 

使用

it { should callback(:some_method).after(:save) } 

谢谢Beat写这个伟大的图书馆。