【问题标题】:RSpec controller test can't get id params. I don't know how to fix thisRSpec 控制器测试无法获取 id 参数。我不知道如何解决这个问题
【发布时间】:2021-03-02 21:25:24
【问题描述】:

您好,我现在正在通过 rspec 为 rails 应用程序进行测试。我不知道要解决这个问题。 在下面。任何人都可以解决这个问题?

1) Items::AddToBasketsController Post #create succuss
     Failure/Error: @item = Item.find(params[:item_id])
     
     ActiveRecord::RecordNotFound:
       Couldn't find Item with 'id'=category=nigiri&discription=test+test&img=%23%3CFile%3A0x00007fc54e9bfc38%3E&name=test1&price=301
     # ./app/controllers/items/add_to_baskets_controller.rb:4:in `create'
     # ./spec/controller/add_to_baskets_controller_spec.rb:43:in `block (4 levels) in <top (required)>'
     # ./spec/controller/add_to_baskets_controller_spec.rb:42:in `block (3 levels) in <top (required)>'

add_to_baskets_controller_spec.rb

require 'rails_helper'


RSpec.describe Items::AddToBasketsController, type: :controller do 
  let(:user) { create(:user) }
  let(:admin) { create(:admin) }
  let(:first_item)  { create(:first_item, admin_id: admin.id) }
  let(:item_params) { attributes_for(:first_item) }
  
  before do 
    login_user
  end
  
  describe "Post #create" do 
    it "succuss" do
      basket = user.prepare_basket
      expect do
        post :create, params: { item_id: FactoryBot.attributes_for(:first_item) }
      end.to change(basket.basket_items, :count).by(1)
    end
  end
end

add_to_baskets_controller.rb

class Items::AddToBasketsController < Items::ApplicationController
  def create
    basket = current_user.prepare_basket
    @item = Item.find(params[:item_id])
    basket.basket_items.create!(item_id: @item.id)
    flash[:success] = "your item in basket"
    redirect_to baskets_path
  end
end

【问题讨论】:

  • 仅供参考,通常它在英语中被称为购物车而不是篮子(我不知道你的母语是什么,但我曾经犯过同样的错误)

标签: ruby-on-rails ruby rspec


【解决方案1】:

上线:

post :create, params: { item_id: FactoryBot.attributes_for(:first_item) }

你说参数item_id应该是FactoryBot.attributes_for(:first_item),这是一个包含first_item所有属性的哈希。

此外,要获取 ID,您需要先创建对象。换句话说:

item_id: FactoryBot.create(:first_item).id

或者简单地说,使用您的let

item_id: first_item.id

【讨论】:

  • 非常感谢。它可以工作。申请你!
猜你喜欢
  • 1970-01-01
  • 2021-08-22
  • 1970-01-01
  • 2022-06-29
  • 1970-01-01
  • 2021-09-15
  • 2022-08-08
  • 1970-01-01
  • 2012-06-22
相关资源
最近更新 更多