You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

accepts_nested_attributes_for在应用生效但Rspec测试不生效问题

问题排查:Rspec测试中嵌套属性未生成关联记录
  • 问题根源
    测试用例中,open_slots_attributes被错误添加到参数的根层级,而非shop参数内部。控制器的shop_params方法从params.require(:shop)中读取嵌套属性,因此无法识别根层级的open_slots_attributes,导致关联的OpenSlot记录未被创建。

  • 错误代码片段
    原测试中的before块赋值逻辑错误:

    before do
        valid_params["open_slots_attributes"] = 
        {
            "start_time": "12:30",
            "end_time": "18:30",
            "day_number": 1
        },
        {
            "start_time": "12:30",
            "end_time": "18:30",
            "day_number": 2
        },
        {
            "start_time": "12:30",
            "end_time": "18:30",
            "day_number": 6
        }
    end
    

    这会生成不符合要求的参数结构:

    {
      shop: { name: "test name" },
      open_slots_attributes: [...] # 不在shop内部,无法被shop_params读取
    }
    
  • 修正后的测试代码
    将open_slots_attributes放入valid_params[:shop]内部,同时用数组包裹多个嵌套对象:

    context 'and when valid open_slots_attribute are present' do
        before do
            valid_params[:shop][:open_slots_attributes] = [
                {
                    start_time: "12:30",
                    end_time: "18:30",
                    day_number: 1
                },
                {
                    start_time: "12:30",
                    end_time: "18:30",
                    day_number: 2
                },
                {
                    start_time: "12:30",
                    end_time: "18:30",
                    day_number: 6
                }
            ]
        end
        it 'create open slots for shop' do
            expect { create_shop }.to change { OpenSlot.count }.by(3)
        end
        # 可选补充验证:确认关联记录归属正确
        it 'associates open slots with the new shop' do
            create_shop
            expect(Shop.last.open_slots.count).to eq(3)
        end
    end
    
  • Postman调用正常的原因
    Postman请求中你应该是将open_slots_attributes正确嵌套在shop对象内部,完全匹配控制器shop_params的参数要求,因此能同时创建Shop和关联的OpenSlot记录。

内容的提问来源于stack exchange,提问作者Anna Bozio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 20:50:15