用于测试验证错误的简单语法

Rom*_*man 8 validation unit-testing ruby-on-rails

我正在寻找干净和简短的代码来测试Rails Unittests中的验证.

目前我做的是这样的

test "create thing without name" do
    assert_raise ActiveRecord::RecordInvalid do
        Thing.create! :param1 => "Something", :param2 => 123
    end
end
Run Code Online (Sandbox Code Playgroud)

我想有更好的方法也显示验证消息?

解:

我目前没有额外框架的解决方案是:

test "create thing without name" do
    thing = Thing.new :param1 => "Something", :param2 => 123
    assert thing.invalid?
    assert thing.errors.on(:name).any?
end
Run Code Online (Sandbox Code Playgroud)

小智 5

您没有提到您正在使用的测试框架.许多宏具有使测试activerecord快速的宏.

在不使用任何测试助手的情况下,这是"漫长的道路":

thing = Thing.new :param1 => "Something", :param2 => 123
assert !thing.valid?
assert_match /blank/, thing.errors.on(:name)
Run Code Online (Sandbox Code Playgroud)

  • 从Rails 3开始,ActiveModel :: Errors没有"on"方法.http://stackoverflow.com/questions/7526499/undefined-method-on-for-actionmodel (2认同)