我正在尝试访问我在混入 RSpec 的模块中在 RSpec 中定义的实例变量,但我似乎无法让它工作。
简化的规范文件显示了我遇到的问题:
my_spec.rb
require 'rspec'
describe 'passing instance variables from specs into ruby mixins' do
it 'should pass the instance variable to the module' do
@a = 'a'
A.a.should == 'a'
end
it 'should pass the instance variable to the module in the module' do
@b = 'b'
A.b.should == 'b'
end
it 'should pass instance varisables from one module to the other' do
A.c.should == 'c'
end
end
module B
def b
return @b
end
def c
return @c
end
end
module A
extend B
@c = 'c'
def self.a
return @a
end
end
结果:
1) passing instance variables from specs into ruby mixins should pass the instance variable to the module
Failure/Error: A.a.should == 'a'
expected: "a"
got: nil (using ==)
# ./spec/my_spec.rb:6:in `block (2 levels) in <top (required)>'
2) passing instance variables from specs into ruby mixins should pass the instance variable to the module in the module
Failure/Error: A.b.should == 'b'
expected: "b"
got: nil (using ==)
# ./spec/my_spec.rb:11:in `block (2 levels) in <top (required)>'
基本上,我希望能够访问模块 A 和 B 中的实例变量 @a、@b。我尝试过使用类变量 @@a 和 @@b,但这不起作用。
我可以使用全局变量($a 和 $b),这很有效,但我觉得这并不优雅,因为它们是全局变量,它们是 evil。
工作代码:
require 'rspec'
describe 'passing instance variables from specs into ruby mixins' do
it 'should pass the instance variable to the module' do
$a = 'a'
A.a.should == 'a'
end
it 'should pass the instance variable to the module in the module' do
$b = 'b'
A.b.should == 'b'
end
it 'should pass instance varisables from one module to the other' do
A.c.should == 'c'
end
end
module B
def b
return $b
end
def c
return @c
end
end
module A
extend B
@c = 'c'
def self.a
return $a
end
end
有任何想法吗?