我试图让FactoryGirl.attributes_for(:trip)
与HABTM协会:countries
因为控制器测试失败 - :countries
缺席在:trip
属性):如何使用has_and_belongs_to_many关联获取FactoryGirl模型属性?
TripsController:
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
的Gemfile:
factory_girl_rails (4.5.0)
尝试这样:http://makandracards.com/jan0sch/11111-rails-factorygirl-and-has_and_belongs_to_many,但没用。
我曾经尝试使用has_and_belongs_to_many为多对多的,但用来运行到各种问题。我发现使用has_many更容易设置。本教程可能有所帮助:http://blog.teamtreehouse.com/what-is-a-has_many-through-association-in-ruby-on-rails-treehouse-quick-tip – RichardAE