2014-10-16 86 views
1

我有Rails 4应用程序TravelNotes。旅行笔记有三种状态:草稿,已发布,已存档。 如果状态是草稿,那么它可以被删除,否则不可以。ActiveRecord :: RecordNotDestroyed的RSpec匹配器

在TravelNote - 型号:

before_destroy :check_for_draft 

    def check_for_draft 
    if status == 'draft' 
     delete 
    else 
     errors.add(:scope, 'Only drafts can be deleted') 
     return false 
    end 
    end 

我用RSpec的测试:

it "should delete a travel note if its status is draft" do 
    expect{ draft.destroy! }.to change{ TravelNote.count }.by(-1) 
end 


it "should not delete a travel note if its status is published or archived" do 
    expect{ published.destroy! }.to_not change{ TravelNote.count } 

当我运行测试草案,删除,测试通过,但已发布,删除测试我得到:

Failures: 
    1) TravelNote delete should not delete a travel note if its status is published or archived 
Failure/Error: expect{ published.destroy! }.to_not change{ TravelNote.count } 
ActiveRecord::RecordNotDestroyed: 
    ActiveRecord::RecordNotDestroyed 

很明显,代码工作,只有旅行笔记与其他状态比草稿可以被删除。

我该如何将故障消息ActiveRecord :: RecordNotDestroyed变为绿色?

回答

0

我不得不删除一鼓作气摧毁!获得测试通过:

it "should not delete a travel note if its status is published or archived" do 
    expect{ published.destroy }.to_not change{ TravelNote.count } 
    expect{ archived.destroy }.to_not change{ TravelNote.count } 
end 
0

试试这个

expect{ published.destroy! }.to raise_error(ActiveRecord::RecordNotDestroyed) 

欲了解更多信息

http://apidock.com/rails/ActiveRecord/Persistence/destroy%21

+0

谢谢菲利普,你的方法正在工作。但是在消除了爆炸之后!测试也通过了。我不确定这是否是rspec方式来检查,但我坚持“不改变”。 – StandardNerd 2014-10-16 16:52:44

1

有几个问题在这里:

  1. 您正在使用bang!版本的destroy!其胁迫从返回falseraise ActiveRecord::RecordNotDestroyed任何before_destroy回调。
  2. 您在方法中使用delete,在您的测试中使用destroy!delete不会调用回调 - 请参阅Difference between Destroy and Delete
  3. 您不应在before_destroy回拨内呼叫deletedestroyself。不返回false将导致原始的destroy行动起作用。

@Felipe发布的链接到destroy,你也应该看看链接destroy!

http://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-destroy-21

其中规定

有一系列与破坏相关的回调! 。如果before_destroy回调返回false,则操作被取消并销毁!引发ActiveRecord :: RecordNotDestroyed。有关更多详细信息,请参阅ActiveRecord :: Callbacks。

+0

要清楚,您可以'删除'或'销毁'其他相关记录,但是您不应该'self.delete',因为回调为您做了这些 – 2015-02-14 19:36:20