从Rspec传递ruby实例变量以混合ins

时间:2012-06-22 04:29:32

标签: ruby module rspec mixins

我正在尝试访问我在RSpec中定义的实例变量,我在混合到RSpec的模块中,但我似乎无法使其工作。

一个简化的spec文件显示了我遇到的问题:

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,但这不起作用。< / p>

我可以使用全局变量($ a和$ b),这可行,但我觉得这并不优雅,因为它们是全局变量which are 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

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

即使它们共享相同的名称,它们也是单独的作用域,因为它们的作用域是定义它们的实例

也就是说,您在规范中设置的实例变量仅存在于这些规范的范围内。类似地,模块内的实例变量的范围类似于该上下文。

我不确定它是否与你想要完成的内容匹配,因为示例是抽象的,但试试这个:

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的内核。

我是否误解了您要解决的问题?