我正在使用Rspec来测试接收到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
测试帖子,我想确保option.suboptions等于[child]。但我不知道如何将实例子属性传递给suboptions_attributes。我这样做的方式不起作用。
答案 0 :(得分:0)
找到答案:
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
这是一种做法。