我的一个模特中有before_validation :do_something, :on => :create
。
我想测试一下,:save
上不。
有没有一种简洁的方法来测试它(使用Rails 3,Mocha和Shoulda),而不执行以下操作:
context 'A new User' do
# Setup, name test etc
@user.expects(:do_something)
@user.valid?
end
context 'An existing User' do
# Setup, name test etc
@user.expects(:do_something).never
@user.valid?
end
在shoulda API中找不到任何内容,这感觉相当不干......
有什么想法吗?谢谢:))
答案 0 :(得分:9)
我认为你需要改变你的方法。您正在测试Rails是否正常工作,而不是您的代码适用于这些测试。考虑改为测试代码。
例如,如果我有这个相当无聊的类:
class User
beore_validation :do_something, :on => :create
protected
def do_something
self.name = "#{firstname} #{lastname}"
end
end
我实际上会像这样测试它:
describe User do
it 'should update name for a new record' do
@user = User.new(firstname: 'A', lastname: 'B')
@user.valid?
@user.name.should == 'A B' # Name has changed.
end
it 'should not update name for an old record' do
@user = User.create(firstname: 'A', lastname: 'B')
@user.firstname = 'C'
@user.lastname = 'D'
@user.valid?
@user.name.should == 'A B' # Name has not changed.
end
end
答案 1 :(得分:3)
您可能会喜欢shoulda callback matchers。