如何暂时“class_eval”为了测试?

发布于 2024-11-09 14:13:22 字数 649 浏览 3 评论 0原文

是否可以暂时将某些方法应用到一个类中进行测试?我希望能够根据多种应用方式来运行规范。虽然我可以制作一堆具有不同设置的装置,但我发现在测试中仅 class_eval 模型更容易。例如:

describe "some context"
  before do
    Page.class_eval do
      my_applying_method :some => :option
    end
  end

  it "should..."
end

然后在另一个上下文块中:

describe "another context without the gem applied"
  before do
    Page.class_eval do
      # nothing here since I want to page to be as is
    end
  end

  it "should do something else..."
end

但是最后一个上下文块的问题是它有一个修改过的类(在上面的上下文块中修改)。 是否可以在class_eval之后重置课程?如何?

谢谢!

Is it possible to temporarily apply certain methods to a class for tests? I want to be able to run specs depending on many ways to apply it. While I could make a bunch of fixtures with different settings, I find it easier to just class_eval the model in the tests. For example:

describe "some context"
  before do
    Page.class_eval do
      my_applying_method :some => :option
    end
  end

  it "should..."
end

Then in another context block:

describe "another context without the gem applied"
  before do
    Page.class_eval do
      # nothing here since I want to page to be as is
    end
  end

  it "should do something else..."
end

But the problem with the last context block is that it has a modified class (modified in the context block above). Is it possible to reset a class after class_eval? How?

Thanks!

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

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

发布评论

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

评论(2

断爱 2024-11-16 14:13:22

我希望有更好的方法来做到这一点,但您可以使用这个(并且在 Foo = Foo_old 行有一个警告):

module Bar
  def baz
  end
end

class Foo
end

puts Foo.method_defined? :baz #=> false
Foo_old = Foo.dup # create a copy of our class

Foo.class_eval do
  include Bar
end

puts Foo.method_defined? :baz #=> true
Foo = Foo_old
puts Foo.method_defined? :baz #=> false

I hope there is a better way to do that but you can use this(and it's with a warning at the Foo = Foo_old line):

module Bar
  def baz
  end
end

class Foo
end

puts Foo.method_defined? :baz #=> false
Foo_old = Foo.dup # create a copy of our class

Foo.class_eval do
  include Bar
end

puts Foo.method_defined? :baz #=> true
Foo = Foo_old
puts Foo.method_defined? :baz #=> false
泪冰清 2024-11-16 14:13:22

您还没有阐明如何修改该类。

remix 库允许您暂时包含模块并在以后正确地取消包含它。

一般来说,复制类并测试副本可能是最安全的:

irb(main):001:0> class Foo; end
#=> nil
irb(main):002:0> Foo.dup.class_eval{ @x = 42 }
#=> 42
irb(main):003:0> Foo.class_eval{ @x }
#=> nil

You haven't clarified how you are modifying the class.

The remix library allows you to temporarily include a module and properly uninclude it later.

In general, it's probably safest to just duplicate the class and test the duplicate:

irb(main):001:0> class Foo; end
#=> nil
irb(main):002:0> Foo.dup.class_eval{ @x = 42 }
#=> 42
irb(main):003:0> Foo.class_eval{ @x }
#=> nil
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文