2013-05-15 22 views
1

春節說我有類如何阻止傳遞到RSpec的「與」預期

Class Foo < ActiveRecord::Base 

    def set_publication 
     Publication.new do |publication| 
     publication.owner_type = 'Foo' 
     publication.owner_id = 123 
     end 
     return 'something else' 
    end 
end 

問:我如何測試塊出版新的實例將收到

describe Foo, 'set_publication' do 
    let(:foo){ Foo.new } 

    it do 
    Publication.should_recive(:new).with(???????).and_return(double(:something)) 
    foo.set_publication 
    end 
end 
當然

這只是一個非常複雜的功能的例子,我不能使用像這樣的散列參數

Class Foo < ActiveRecord::Base 

    def set_publication 
    Publication.new owner_type: 'Foo', owner_id: 123   
    return 'something else' 
    end 
end 

並測試它像這樣

describe Foo, 'set_publication' do 
    let(:foo){ Foo.new } 

    it do 
    Publication.should_recive(:new).with(owner_type: "Foo", owner_id: 123).and_return(double(:something)) 
    foo.set_publication 
    end 
end 

謝謝


UPDATE:這似乎是有點不清楚我問這裏有什麼,所以:

我在尋找確保Publication.new被顯式調用一組參數,在這種情況下,一個塊

so我想這樣的事情

Publication.should_receive(:new).with(&block) # example 

其中塊參數owner_type == '富' 和owner_id == 123

回答

1

您可以使用and_yield做到這一點。

class Foo 
    def set_publication 
    Publication.new do |publication| 
     publication.owner_type = 'Foo' 
     publication.owner_id = 123 
    end 
    return 'something else' 
    end 
end 

class Publication 
    attr_accessor :owner_id, :owner_type 

    def initialize 
    yield self if block_given? 
    end 
end 

和規範

describe Foo do 
    let(:foo) { Foo.new } 
    let!(:publication) { Publication.new } 

    it do 
    Publication.should_receive(:new).and_yield(publication) 

    foo.set_publication 

    publication.owner_type.should eq 'Foo' 
    publication.owner_id.should eq 123 
    end 
end 
+0

非常優雅,thx – equivalent8

0

我唯一可能的(工作)解決方案中辛勤爲:

Class Foo < ActiveRecord::Base 

    def set_publication 
     Publication.new &publication_block_params(123) 
     return 'something else' 
    end 

    def publication_block_params(some_id) 
    Proc.new do |publication| 
     publication.owner_type = 'Foo' 
     publication.owner_id = some_id # could be self.id but let's keep it this way 
    end 
    end 

end 

和規格

describe Foo, 'set_publication' do 
    let(:foo){ Foo.new } 
    let(:my_block){ Proc.new {} } 

    it do 
    foo.should_receive(:publication_block_params).with(123).and_return(my_block) 
    Publication.should_receive(:new).with(&my_block).and_return(double(:something)) 

    foo.set_publication 
    end 
end 

,比單獨創建一個規範用於發佈阻止參數

describe Foo, 'publication_block_params' do 
    let(:foo){ Foo.new } 

    it do  
    publication = Publication.new &foo.publication_block_params(123) 
    publication.owner_id.should be 123 
    publication.owner_type.should be 'Foo' 
    end 
end