0

我正在尝试访问我在混入 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

有任何想法吗?

4

1 回答 1

1

尽管它们共享相同的名称,但它们的作用域是分开的,因为它们的作用域仅限于定义它们的实例。

也就是说,你在specs中设置的实例变量只存在于那些specs的范围内。类似地,模块内的实例变量也同样适用于该上下文。

鉴于示例是抽象的,我不确定它是否与您要完成的任务相匹配,但试试这个:

require 'rspec'

module B
  def b= b
    @b = b
  end

  def b
    return @b
  end

  def c= c
    @c = c
  end

  def c
    return @c
  end
end

module A
  extend B

  @c = 'c'

  def self.a= a
    @a = a
  end

  def self.a
    return @a
  end
end

describe 'passing instance variables from specs into ruby mixins' do
  it 'should pass the instance variable to the module' do
    A.a = 'a'
    A.a.should == 'a'
  end

  it 'should pass the instance variable to the module in the module' do
    A.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

然后可以简化使用attr_accessor,而不是手动定义 getter/setter 方法。

问题是您只是在测试 Ruby 的核心。

我误解了您要解决的问题吗?

于 2012-06-22T04:48:40.697 回答