如何将模块混合到 rspec 上下文中 [英] How to mix a module into an rspec context

查看:45
本文介绍了如何将模块混合到 rspec 上下文中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将模块混合到 rspec 上下文(又名 describe)中,以便模块的常量可用于规范?

How can I mix a module into an rspec context (aka describe), such that the module's constants are available to the spec?

module Foo
  FOO = 1
end

describe 'constants in rspec' do

  include Foo

  p const_get(:FOO)    # => 1
  p FOO                # uninitialized constant FOO (NameError)

end

const_get 可以在常量名不感兴趣的情况下检索常量.是什么导致了 rspec 的奇怪行为?

That const_get can retrieve the constant when the name of the constant cannot is interesting. What's causing rspec's curious behavior?

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

I am using MRI 1.9.1 and rspec 2.8.0. The symptoms are the same with MRI 1.8.7.

推荐答案

你可以使用RSpec的shared_context:

You can use RSpec's shared_context:

shared_context 'constants' do
  FOO = 1
end

describe Model do
  include_context 'constants'

  p FOO    # => 1
end

这篇关于如何将模块混合到 rspec 上下文中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆