2015-09-14 77 views
3

我試圖讓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,但沒用。

+0

我曾經嘗試使用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

回答

2

下面是解釋了答案:

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] 
} 
0

檢查您是否確實在您的請求中發送任何countries_ids

請更新您的帖子,其值爲attributes_for(:trip)

+0

嗨Alexey,問題不在控制器中,但在FactoryGirl.attributes_for –

+0

嗨,其實我的意思是說你不會在這行代碼中發送'countries_ids':'之前{post:create,trip:attributes_for(:trip)}',但我還不確定。很高興你已經解決它自己。 –

相關問題