2009-09-26 12 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

ありがとう返信用に私はrspecと他の人にしばらくお試しになります。今のところ私はassert(record.invalid?)とassert_equal([]、record.errors.full_messages)を使って自分自身を手助けします。 – Roman

答えて

6

あなたは何をテストあなたが使用しているフレームワークを言及していません。多くの人が、アクティブなレコードをテストするマクロを持っています。ここで

は、すべてのテストヘルパーを使用せずにそれを行うには、「長い道のり」です:

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

私は現時点では単純なRailsしか使用していません。 – Roman

+1

Rails 3では、ActiveModel :: Errorsの "on"メソッドはありません。 http://stackoverflow.com/questions/7526499/undefined-method-on-for-actionmodel –

+1

この回答は日付があるかもしれませんが、 'assert_match'は配列に対しては機能しません。 –

0

あなたはrspec-on-rails-matchersを試してみることができます。あなたのような構文で提供されます。

@thing.should validates_presence_of(:name) 
+0

ページに「私を使わないでください。私は時代遅れで、私はうまくいきません。 rspecで動作するはずです。それを使用してください。 – Roman

1

accept_values_for宝石を試してみてください。 それはこのような何か行うことができます:あなたは私はRailsの2.0.5を使用しています簡単に

1

を本当に複雑な検証をテストすることができます。このように

describe User do 

    subject { User.new(@valid_attributes)} 

    it { should accept_values_for(:email, "[email protected]", "[email protected]") } 
    it { should_not accept_values_for(:email, "invalid", nil, "[email protected]", "[email protected]") } 
end 

を、と私は主張したいときにモデルが失敗すること検証、私は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コントローラが作成または更新要求の後にエラーメッセージを出さないことを確認することができます。 Railsの3.2.1とアップを使用してそれらのために

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

、私は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