0

注意:一個企業有許多目錄,有產品,目錄有許多產品。這些關聯是正確定義的,他們正在應用程序的前端工作。但我無法通過此測試。我使用friendly_id所以你會使用一些的查找方法@ model.slugRails工廠女孩RSpec測試擁有多種嵌套資源關係

我想這個測試出來見我

describe "GET 'show'" do 
    before do 
    @business = FactoryGirl.create(:business) 
    @catalog = FactoryGirl.create(:catalog, :business=>@business) 
    @product1 = FactoryGirl.create(:product, :business=>@business, :catalog=>@catalog) 
    @product2 = FactoryGirl.create(:product, :business=>@business, :catalog=>@catalog) 
    end 

    def do_show 
    get :show, :business_id=>@business.slug, :id=>@catalog.slug 
    end 

    it "should show products" do 
    @catalog.should_receive(:products).and_return([@product1, @product2]) 
    do_show 
    end 
end 

使用此工廠(注意,業務和產品目錄工廠定義別的地方,他們協會):

FactoryGirl.define do 
    sequence :name do |n| 
    "product#{n}" 
    end 

    sequence :description do |n| 
    "This is description #{n}" 
    end 

    factory :product do 
    name 
    description 
    business 
    catalog 
    end 
end 

這個show動作:

def show 
    @business = Business.find(params[:business_id]) 
    @catalog = @business.catalogs.find(params[:id]) 
    @products = @catalog.products.all 
    respond_with(@business, @catalog) 
    end 

但我收到此錯誤:

CatalogsController GET 'show' should show products 
    Failure/Error: @catalog.should_receive(:products).and_return([@product1, @product2]) 
     (#<Catalog:0x000001016185d0>).products(any args) 
      expected: 1 time 
      received: 0 times 
    # ./spec/controllers/catalogs_controller_spec.rb:36:in `block (3 levels) in <top (required)>' 

此外,該代碼塊也表明,商業模式尚未收到find方法:

Business.should_receive(:find).with(@business.slug).and_return(@business) 
+0

什麼錯誤你有沒有得到Business.should_receive,預計1次相同,收到0次? –

回答

1

這裏的問題是,@catalog實例變量您在規範中設置的內容與控制器中的@catalog實例變量不同。

spec中的@catalog將永遠不會收到任何發送到控制器中的@catalog的消息。

你需要做的,而不是什麼是你的規格可以改變:

@catalog.should_receive(:products).and_return([@product1, @product2]) 

Catalog.any_instance.should_receive(:products).and_return([@product1, @product2]) 

檢查出any_instance.should_receive RSpec的文檔在這裏:https://www.relishapp.com/rspec/rspec-mocks/v/2-6/docs/message-expectations/expect-a-message-on-any-instance-of-a-class

+0

真棒。請注意,雖然這一行:「@products = @ catalog.products.all」給了我一個'未定義的方法'all'for '。刪除'.all'使得測試通過 – yretuta

+0

很好,很高興你能對它進行排序。 :) –