2014-04-12 101 views
8

我想测试在类继承期间运行的逻辑,但在运行多个断言时遇到了问题。如何使用rspec测试ruby继承

我第一次尝试......

describe 'self.inherited' do 
    before do 
    class Foo 
     def self.inherited klass; end 
    end 

    Foo.stub(:inherited) 

    class Bar < Foo; end 
    end 

    it 'should call self.inherited' do 
    # this fails if it doesn't run first 
    expect(Foo).to have_received(:inherited).with Bar 
    end 

    it 'should do something else' do 
    expect(true).to eq true 
    end 
end 

但这种失败,因为酒吧类已经被加载,因此不叫inherited第2个时间。如果断言不首先运行......它会失败。

于是我想是这样......

describe 'self.inherited once' do 
    before do 
    class Foo 
     def self.inherited klass; end 
    end 

    Foo.stub(:inherited) 

    class Bar < Foo; end 
    end 

    it 'should call self.inherited' do 
    @tested ||= false 
    unless @tested 
     expect(Foo).to have_receive(:inherited).with Bar 
     @tested = true 
    end 
    end 

    it 'should do something else' do 
    expect(true).to eq true 
    end 
end 

因为@tested不从测试坚持到测试,测试不只是运行一次。

任何人有任何聪明的方法来实现这一目标?这是一个人为的例子,我不实际上需要测试红宝石本身;)

+0

测试的行为,而不是执行。测试类是否从继承类继承将是合理的,只有当方法在做元编程的东西时(比如构造类和设置祖先) –

回答

24

这里有一个简单的方法来测试类继承使用RSpec:

鉴于

class A < B; end 

一个更简单的方法使用RSpec来测试继承:

describe A 
    it { expect(described_class).to be < B } 
end 
+1

好的答案!解释可以在这里找到:http://ruby-doc.org/core-2.3.0/Module.html#method-i-3C –

0

使测试过程中进行测试的继承运行类定义:

describe 'self.inherited' do 

    before do 
    class Foo 
     def self.inherited klass; end 
    end 
    # For testing other properties of subclasses 
    class Baz < Foo; end 
    end 

    it 'should call self.inherited' do 
    Foo.stub(:inherited) 
    class Bar < Foo; end 
    expect(Foo).to have_received(:inherited).with Bar 
    end 

    it 'should do something else' do 
    expect(true).to eq true 
    end 
end 
+0

这么简单...当然只是使用不同的类......谢谢! – brewster

1

由于某种原因,我没有管理solution from David Posey工作(我想我做错了什么。随意在评论中提供解决方案)。如果有人在那里有同样的问题,这个工程太:

describe A 
    it { expect(described_class.superclass).to be B } 
end 
1

这样的事情

class Child < Parent; end 

我通常做的:

it 'should inherit behavior from Parent' do 
    expect(Child.superclass).to eq(Parent) 
end