rspec rails nested_attributes 在控制器上

rspec rails nested_attributes on controller

我正在使用 Rspec 来测试接收到 nested_attributes 的控制器。 class 选项可以 has_many 子选项。

models/suboption.rb:

class Suboption < ApplicationRecord
  belongs_to :option,
  optional: true

  validates :name, presence: true
end

models/option.rb:

class Option < ApplicationRecord
  belongs_to :activity
  has_many :suboptions, dependent: :destroy

  accepts_nested_attributes_for :suboptions, allow_destroy: true,

    reject_if: ->(attrs) { attrs['name'].blank? }

  validates :name, presence: true
end

参数:

def option_params
    params.require(:option).permit(:name, :activity_id, :students_ids => [], suboptions_attributes: [:id, :name, :_destroy])
  end

spec/controller/options_controller_spec.rb:

describe "POST #create" do
        let(:option) { assigns(:option) }
        let(:child) { create(:suboption) }

        context "when valid" do
          before(:each) do
            post :create, params: {
              option: attributes_for(
                :option, name: "opt", activity_id: test_activity.id,
                suboptions_attributes: [child.attributes]
              )
            }
          end

          it "should redirect to options_path" do
            expect(response).to redirect_to options_path
          end

          it "should save the correctly the suboption" do
            expect(option.suboptions).to eq [child]
          end
        end

正在测试 Post,我想确保 option.suboptions 等于 [child]。但是我不知道如何将实例child的属性传递给suboptions_attributes。我这样做是行不通的。

找到答案:

describe "POST #create" do
    let(:option) { assigns(:option) }

    context "when valid" do
      before(:each) do
        post :create, params: {
          option: attributes_for(:option, name: "opt", activity_id: test_activity.id,
            suboptions_attributes: [build(:option).attributes]
          )
        }
      end

      it "should save suboptions" do
        expect(option.suboptions.first).to be_persisted
        expect(Option.all).to include option.suboptions.first
      end

      it "should have saved the same activity_id for parent and children" do
        expect(option.suboptions.first.activity_id).to eq option.activity_id
      end
    end

这是一种方法。