2016-11-24 131 views
0

我在我的應用程序測試失敗的期望

class CartsController < ApplicationController 
    def show 
    @cart = Cart.find(session[:cart_id]) 
    @products = @cart.products 
    end 
end 

有車控制器,寫測試cartscontroller_spec.rb

RSpec.describe CartsController, type: :controller do 
    describe 'GET #show' do 
    let(:cart_full_of){ create(:cart_with_products, products_count: 3)} 
    before do 
     get :show 
    end 
    it { expect(response.status).to eq(200) } 
    it { expect(response.headers["Content-Type"]).to eql("text/html; charset=utf-8")} 
    it { is_expected.to render_template :show } 
    it 'should be products in current cart' do 
     expect(assigns(:products)).to eq(cart_full_of.products) 
    end 
    end 
end 

我factories.rb看起來這樣:

factory(:cart) do |f| 
    f.factory(:cart_with_products) do 
    transient do 
     products_count 5 
    end 
    after(:create) do |cart, evaluator| 
     create_list(:product, evaluator.products_count, carts: [cart]) 
    end 
    end 
end 

factory(:product) do |f| 
    f.name('__product__') 
    f.description('__well-description__') 
    f.price(100500) 
end 

,但我出現錯誤:

FCartsController GET #show should be products in current cart 
Failure/Error: expect(assigns(:products)).to eq(cart_full_of.products) 

    expected: #<ActiveRecord::Associations::CollectionProxy [#<Product id: 41, name: "MyProduct", description: "Pro...dDescription", price: 111.0, created_at: "2016-11-24 11:18:43", updated_at: "2016-11-24 11:18:43">]> 
     got: #<ActiveRecord::Associations::CollectionProxy []> 

貌似我沒有創造出來的產品,因爲在空的產品模型排列的ActiveRecord ::協會所有:: CollectionProxy [],同時,我調查product`s ID是與每個測試attempt.At的那一刻我沒有增加堅實的想法是錯誤的

回答

0

創建的cartid未分配給您的get :show的會話。

before do 
    session[:cart_id] = cart_full_of.id 
    get :show 
end 

# or 

before do 
    get :show, session: { cart_id: cart_full_of.id } 
end 

UPDATE:

你在控制器find需要session[:cart_id]價值,但你的測試沒有這些數據提供給控制器的請求。如果您使用上述代碼之一,則測試請求將會話提供給控制器。 !

+0

太好了,我已經rewrited得到:顯示,會話:{cart_id:cart_full_of.id} 和它發射,但你可以少解釋爲什麼你sugession工作? –