ruby – 如何将模块混合到rspec上下文中

前端之家收集整理的这篇文章主要介绍了ruby – 如何将模块混合到rspec上下文中前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何将模块混合到rspec上下文中(也称为描述),以使模块的常量可用于规范?
  1. module Foo
  2. FOO = 1
  3. end
  4.  
  5. describe 'constants in rspec' do
  6.  
  7. include Foo
  8.  
  9. p const_get(:FOO) # => 1
  10. p FOO # uninitialized constant FOO (NameError)
  11.  
  12. end

当常量的名称不能很有趣时,const_get可以检索常量.是什么导致rspec好奇的行为?

我使用的是MRI 1.9.1和rspec 2.8.0.症状与MRI 1.8.7相同.

解决方法

您可以使用RSpec的shared_context:
  1. shared_context 'constants' do
  2. FOO = 1
  3. end
  4.  
  5. describe Model do
  6. include_context 'constants'
  7.  
  8. p FOO # => 1
  9. end

猜你在找的Ruby相关文章