测试失败的期望

问题描述:

我在我的应用程序测试失败的期望

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的那一刻我没有增加坚实的想法是错误的

创建的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工作? –