Shoulda / RSpec:确保validation消息“xxx”已打开:base

我仍然非常困惑什么是it { should have(1).error_on(:base) }背后的魔法it { should have(1).error_on(:base) }以及什么是特定的Shoulda匹配器。

我想确保:base包含错误消息“xxx”,那么我该怎么做呢?

 it "should contain error message 'xxx'" do contact.valid? contact.errors[:base].should include('xxx') end 

这是“走的路”,还是更好的? 谢谢。

对,它看起来不错。 内联rspec测试正在使用主题。 您可以像这样重写您的测试:

 describe 'my method' do before { contact.valid? } context 'contact is not valid' do subject { contact.errors[:base] } it { should include 'xxx' } end end 

在该主题上调用should方法。 它有时可以更具可读性。 而且您不必为不言自明的规格编写说明;-)