“这里的方法”在鲁比?

发布于 2024-11-01 11:25:56 字数 936 浏览 1 评论 0原文

我正在编写一些帮助程序来干燥我的测试。我想象了这样的事情:

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

佼人 2024-11-08 11:25:56

你见过舒达吗?它非常适合测试常见的 Rails 功能,例如验证、关系等。 https://github.com/thoughtbot/shoulda -匹配器

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

冷情 2024-11-08 11:25:56

在这种情况下,似乎 class_eval 是必要的,因为我想将变量名称插入实际代码中。

此处说明。

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

Illustrated here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文