我有一个具有一对多关系的模型,它们是Poll
和Choice
。
如何正确测试它们,因为以下代码会导致ActiveRecord::RecordInvalid:
错误。我想要在创建父对象(Poll
)时同时创建其子对象(Choice
),而不是先创建父对象(Poll
),然后再保存子对象(Choice
)。
以下是代码:
首先,这是我在所有测试用例中遇到的错误:
Failure/Error: @poll = FactoryGirl.build(:poll_with_choices, user: @user)
ActiveRecord::RecordInvalid:
Validation failed: Choices choices required at least 2
投票模型:
class Poll < ActiveRecord::Base
belongs_to :user
has_many :choices
accepts_nested_attributes_for :choices
validates :title, presence: true
validates_each :choices do |record, attr, value|
record.errors.add attr, "choices required at least 2" if record.choices.length < 2
end
end
投票工厂:
FactoryGirl.define do
factory :poll do
title { FFaker::Lorem.phrase }
description { FFaker::Lorem.sentences }
user
factory :poll_with_choices do
transient do
choices_count 3
end
after(:build) do |poll, evaluator|
build_list(:choice, evaluator.choices_count)
end
end
end
end
选择工厂:
FactoryGirl.define do
factory :choice do
label { FFaker::Name.name }
votes 0
poll
end
end
调查规范
require 'rails_helper'
RSpec.describe Poll, type: :model do
before do
@user = FactoryGirl.create(:user)
@poll = FactoryGirl.build(:poll_with_choices, user: @user)
end
subject { @poll }
it { should respond_to(:title) }
it { should respond_to(:description) }
it { should validate_presence_of(:title) }
it { should belong_to(:user) }
it { should have_many(:choices) }
it { should accept_nested_attributes_for(:choices) }
describe "#save" do
before do
@user = FactoryGirl.create(:user)
end
it "success" do
poll = FactoryGirl.build(:poll_with_choices, user: @user)
expect(poll.save).to eql true
end
it "fail" do
poll = FactoryGirl.build(:poll, user: @user)
poll.choices = FactoryGirl.build_list(:choice, 1)
expect(poll.save).to eql false
end
end
end
作为 FactoryGirl.create 的参考,而不是 FactoryGirl.build:http://www.rubydoc.info/gems/factory_girl/file/GETTING_STARTED.md#Associations。提前感谢。