开发者

"Here methods" in Ruby?

I'm writing a few helpers to DRY up my tests. I pictured something like:

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

So that this:

class MemberTest < ActiveSupport::TestCase

  test_presence_validation_of :member, :name
end

Executes exactly this at MemberTest class scope:

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

Is it possible to do it this way (with a few adaptations, of course; I doubt my "picture" works), or do I have to use class_eval?


Have you seen Shoulda? It's great for testing common Rails functionality such as validations, relationships etc. https://github.com/thoughtbot/shoulda-matchers


In this case, it seems class_eval is necessary since I want to interpolate variable names into actual code.

Illustrated here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜