2013-08-20 22 views
13

Làm thế nào tôi có thể còn sơ khai một phương pháp trong một mô-đun:RSpec - còn sơ khai phương pháp mô-đun

module SomeModule 
    def method_one 
     # do stuff 
     something = method_two(some_arg) 
     # so more stuff 
    end 

    def method_two(arg) 
     # do stuff 
    end 
end 

tôi có thể kiểm tra method_two trong sự cô lập tốt.

Tôi muốn thử nghiệm method_one trong sự cô lập quá bởi stubbing giá trị trả về của method_two:

shared_examples_for SomeModule do 
    it 'does something exciting' do 
     # neither of the below work 
     # SomeModule.should_receive(:method_two).and_return('MANUAL') 
     # SomeModule.stub(:method_two).and_return('MANUAL') 

     # expect(described_class.new.method_one).to eq(some_value) 
    end 
end 

describe SomeController do 
    include_examples SomeModule 
end 

Các thông số kỹ thuật trong SomeModule được bao gồm trong SomeController thất bại vì method_two ném một ngoại lệ (nó cố gắng để làm một db tra cứu chưa được gieo hạt).

Làm cách nào để có thể khai báo method_two khi được gọi trong vòng method_one?

+0

nghiêm trọng? tại sao downvote? – Harry

+0

bạn mong đợi điều gì từ mô-đun này? là một mixin hoặc gọi phương thức từ nó ở cấp lớp như: 'SomeModule.foo'? – apneadiving

+2

Hãy tận tâm, George. Downvotes trên các câu hỏi là một ý tưởng chung xấu, theo ý kiến ​​của tôi, nhưng tin tốt là những người không thích hợp thường xuyên kích thích upvotes đối kháng, với một đại diện net giành chiến thắng cho bạn và không có tác động bỏ phiếu net. –

Trả lời

2
shared_examples_for SomeModule do 
    let(:instance) { described_class.new } 

    it 'does something exciting' do 
    instance.should_receive(:method_two).and_return('MANUAL') 
    expect(instance.method_one).to eq(some_value) 
    end 
end 

describe SomeController do 
    include_examples SomeModule 
end 
+15

Hãy cố gắng bao gồm một số giải thích về những gì đang xảy ra và lý do của bạn đằng sau điều này. –

Các vấn đề liên quan