2013-10-18 78 views

回答

1

首先,我会说你应该抛出异常时意外ARGS进来的构造。假设你正在返回异常,对于这个类来说,测试其实很简单。这应该让你开始:

# spec/lib/source_socket_spec.rb 

describe SourceSocket do 

    subject { source_socket } 

    let(:source_socket) { SourceSocket.new(address, port, buffer) } 

    let(:address) { double :address, class: SourceAddress, ip: '1.2.3.4' } 
    let(:port) { double :port, class: SourcePort, num: 9876  } 
    let(:buffer) { double :buffer, class: SourceBuffer     } 

    describe '#new' do 
    context 'when the arguments are of the correct types' do 
     it 'assigns the expected variables' do 
     subject 
     assigns(:address).should eq '1.2.3.4' 
     assigns(:buffer).should eq buffer 
     assigns(:port).should eq 9876 
     end 
    end 

    context 'when the arguments are of incorrect types' do 
     context 'when the address is of incorrect type' do 
     let(:address) { double :address } 
     expect { subject }.to raise_error('Error: Address argument is wrong type.') 
     end 

     context 'when the port is of incorrect type' do 
     let(:port) { double :port } 
     expect { subject }.to raise_error('Error: Port argument is wrong type.') 
     end 

     context 'when the buffer is of incorrect type' do 
     let(:buffer) { double :buffer } 
     expect { subject }.to raise_error('Error: Buffer must be a SourceBuffer object!') 
     end 
    end 
    end 

    describe '#to_s' do 
    its(:to_s) { should eq '1.2.3.4:9876' } 
    end 

    describe '#open' do 
    subject { source_socket.open(engine) } 
    let(:engine) { double(:engine) } 

    let(:socket) { double(:socket, connect: nil) } 
    let(:packed) { double(:packed) } 

    before do 
     Socket.stub(:new).and_return(socket) 
     Socket.stub(:pack_sockaddr_in).and_return(packed) 
    end 

    it 'assigns the engine variable' do 
     subject 
     assigns(:engine).should_not be_nil 
    end 

    it 'instantiates a Socket' do 
     Socket.should_receive(:new).with(Socket::PF_INET, Socket::SOCK_DGRAM) 
     subject 
    end 

    it 'assigns the socket variable' do 
     subject 
     assigns(:socket).should_not be_nil 
    end 

    it 'packs up the port and host' do 
     Socket.should_receive(:pack_sockaddr_in).with(9876, '1.2.3.4') 
     subject 
    end 

    it 'connects the socket' do 
     socket.should_receive(:connect).with(packed) 
    end 
    end 
end 

只要记住,有许多方法来测试,而RSpec docs是你最好的朋友。

+0

是的,我需要真正适应RSpec。这是我第一个认真的Ruby项目,我最初将使用TDD,并且由于不知道测试框架而感到恐惧。 我从来没有用我曾经玩过的其他语言进行过单元测试,所以我想我也没有任何参考资料可供借鉴。非常感谢,我一定会搞砸这个。 我认为我个人最大的问题是理解模拟对象,双打和东西。 – MisutoWolf

相关问题