gpt4 book ai didi

ruby-on-rails - 如何获取具有 has_and_belongs_to_many 关联的 FactoryGirl 模型属性?

转载 作者:数据小太阳 更新时间:2023-10-29 08:03:27 28 4
gpt4 key购买 nike

我正在尝试使用 HABTM 关联 :countries 获取 FactoryGirl.attributes_for(:trip) 因为 Controller 测试失败 - :countries 不存在在 :trip 属性中:

旅行 Controller :

class TripsController < ApplicationController
def create
trip = Trip.new(create_params)
if trip.save
redirect_to trips_path, notice: 'Trip successfully created.'
else
redirect_to :back, alert: trip.errors.full_messages.join('<br>').html_safe
end
end

def create_params
params.require(:trip).permit(:end_date, :description, country_ids: [], countries: [])
end
end

RSpec TripsController 测试:

describe TripsController do
describe 'POST #create' do
before { post :create, trip: attributes_for(:trip) }
it { is_expected.to redirect_to trips_path }
end
end

行程模型:

class Trip < ActiveRecord::Base
# Associations
has_and_belongs_to_many :countries

#Validations
validate :require_at_least_one_country

private

def require_at_least_one_country
if country_ids.empty? && countries.count == 0
errors.add(:base, 'Please select at least one country')
end
end
end

旅行工厂:

FactoryGirl.define do
factory :trip do
description { Faker::Lorem.sentence }
end_date { DateTime.now + 1.day }

after(:build) do |trip, evaluator|
trip.countries << FactoryGirl.create(:country, :with_currencies)
end
end
end

gem 文件:

factory_girl_rails (4.5.0)

试过这个:http://makandracards.com/jan0sch/11111-rails-factorygirl-and-has_and_belongs_to_many , 但没用。

最佳答案

这是带有解释的答案:

FactoryGirl.define do
factory :trip do
description { Faker::Lorem.sentence }
end_date { DateTime.now + 1.day }

after(:build) do |trip, evaluator|
trip.countries << FactoryGirl.create(:country, :with_currencies)
end
end
end

FactoryGirl.attributes_for(:trip) 返回

{
:description=>"Eum alias tenetur odit voluptatibus inventore qui nobis.",
:end_date=>Wed, 16 Sep 2015 11:48:28 +0300
}

.

FactoryGirl.define do
factory :trip do
description { Faker::Lorem.sentence }
end_date { DateTime.now + 1.day }
country_ids { [FactoryGirl.create(:country, :with_currencies).id] }
end
end

FactoryGirl.attributes_for(:trip) 返回

{
:description=>"Assumenda sapiente pariatur facilis et architecto in.",
:end_date=>Wed, 16 Sep 2015 11:45:22 +0300,
:country_ids=>[4]
}

关于ruby-on-rails - 如何获取具有 has_and_belongs_to_many 关联的 FactoryGirl 模型属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32558059/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com