【问题标题】:Failed test expectation失败的测试预期
【发布时间】:2016-11-24 12:09:23
【问题描述】:

我的应用中有一个购物车控制器

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

我的 factory.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::Associations::CollectionProxy [] 为空,看起来我根本没有创建产品,同时,我调查产品的 id 随着每次测试尝试而增加。目前我没有实体错误的想法

【问题讨论】:

    标签: ruby-on-rails factory-bot rspec-rails


    【解决方案1】:

    创建的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
    

    更新:

    您在控制器中的find 需要session[:cart_id] 值,但您的测试没有将此数据提供给控制器请求。如果您使用上面的代码之一,测试请求会向控制器提供会话。

    【讨论】:

    • 太棒了!我已经重写了 get :show , session: { car​​t_id: cart_full_of.id } 并且它被解雇了,但是你能解释一下为什么你的 sugession 有效吗?
    猜你喜欢
    • 2013-01-30
    • 1970-01-01
    • 2017-12-20
    • 2021-09-15
    • 1970-01-01
    • 2017-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多