2017-01-10 11 views
0

Nested_attributesを受信したコントローラをテストするためにRspecを使用しています。オプションクラスはhas_manyサブオプションを持つことができます。rspec railsコントローラのnested_attributes

モデル/ suboption.rb:

class Suboption < ApplicationRecord 
    belongs_to :option, 
    optional: true 

    validates :name, presence: true 
end 

モデル/ 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 

PARAMS:

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

スペック/コントローラ/ 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 

Testing Post、私はoption.suboptionsが[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 

これはそれを行う方法です:

答えて

0

は答えを見つけました。

関連する問題