1

テストを DRY するためのヘルパーをいくつか書いています。私は次のようなものを描いた:

class ActiveSupport::TestCase

  def self.test_presence_validation_of model, attribute
    test "should not save #{model.to_s} with null #{attribute.to_s}", <<-"EOM"
      #{model.to_s} = Factory.build #{model.to_sym}, #{attribute.to_sym} => nil
      assert !#{model.to_s}.save, '#{model.to_s.capitalize} with null #{attribute.to_s} saved to the Database'
    EOM
    # Another one for blank attribute.
  end
end

したがって、これは次のとおりです。

class MemberTest < ActiveSupport::TestCase

  test_presence_validation_of :member, :name
end

MemberTestクラススコープでこれを正確に実行します:

test 'should not save member with null name' do
  member = Factory.build :member, :name => nil
  assert !member.save, 'Member with null name saved to the Database'
end

このようにすることは可能ですか(もちろん、いくつかの適応があります。私の「写真」が機能するとは思えません)、または使用する必要がありますclass_evalか?

4

2 に答える 2

3

ショルダを見たことがありますか?検証、関係などの一般的な Rails 機能をテストするのに最適です。https://github.com/thoughtbot/shoulda-matchers

于 2011-04-13T21:38:16.753 に答える
0

この場合、class_eval変数名を実際のコードに補間したいので必要なようです。

ここに示されています。

于 2011-04-14T17:39:48.323 に答える