2009-09-26 68 views
6

我正在寻找简洁的代码来测试Rails Unittests中的验证。测试的简单语法验证错误

目前,我做这样的事情

test "create thing without name" do 
    assert_raise ActiveRecord::RecordInvalid do 
     Thing.create! :param1 => "Something", :param2 => 123 
    end 
end 

我想有一个更好的方式,也显示了验证消息?

解决方案:

我不需要额外的框架目前的解决方案是:

test "create thing without name" do 
    thing = Thing.new :param1 => "Something", :param2 => 123 
    assert thing.invalid? 
    assert thing.errors.on(:name).any? 
end 
+0

谢谢s的答复。我会尝试rspec和其他一些时间。现在我用assert(record.invalid?)和assert_equal([],record.errors.full_messages)帮助自己 – Roman 2009-09-29 09:07:31

回答

6

你不提,你正在使用的测试框架。许多宏都使得测试activerecord快照。

这里的“漫长的道路”做到这一点,而无需使用任何测试助手:

thing = Thing.new :param1 => "Something", :param2 => 123 
assert !thing.valid? 
assert_match /blank/, thing.errors.on(:name) 
+0

目前我只使用普通的Rails。 – Roman 2009-09-29 09:10:03

+1

从Rails 3开始,ActiveModel :: Errors没有“on”方法。 http://stackoverflow.com/questions/7526499/undefined-method-on-for-actionmodel – 2013-01-24 14:31:02

+1

这个答案可能会过时,但'assert_match'不适用于数组。 – 2014-05-09 14:54:45

0

你可以给rspec-on-rails-matchers一试。为您提供如下语法:

@thing.should validates_presence_of(:name) 
+0

该页面说:不要使用我。我过时了,我打破了应该。 Shoulda现在可以使用rspec。使用它。 – Roman 2009-09-29 09:09:20

1

我使用Rails 2.0.5,当我想要断定模型将失败验证,我检查errors.full_messages method,并将其与预期消息数组进行比较。

created = MyModel.new 
created.field1 = "Some value" 
created.field2 = 123.45 
created.save 

assert_equal(["Name can't be blank"], created.errors.full_messages) 

为了声明验证成功,我只是比较一个空数组。你可以做一些非常相似的事情来检查Rails控制器在创建或更新请求后是否没有错误消息。

assert_difference('MyModel.count') do 
    post :create, :my_model => { 
    :name => 'Some name' 
    } 
end 

assert_equal([], assigns(:my_model).errors.full_messages) 
assert_redirected_to my_model_path(assigns(:my_model)) 
1

对于那些使用Rails 3.2.1和起来,我更喜欢使用的方法added?

assert record.errors.added? :name, :blank 

我使用测试帮手,看起来像这样:

def assert_invalid(record, options) 
    assert_predicate record, :invalid? 

    options.each do |attribute, message| 
    assert record.errors.added?(attribute, message), "Expected #{attribute} to have the following error: #{message}" 
    end 
end 

这允许我写这样的测试:

test "should be invalid without a name" do 
    user = User.new(name: '') 

    assert_invalid user, name: :blank 
end