2015-11-23 220 views
0

我無法讓我的控制器測試工作了,我添加了自定義驗證模型。Rails Rspec控制器測試has_and_belongs_to_many

模型的樣子:

push_entry.rb

belongs_to :push_provider 
    has_and_belongs_to_many :push_categories 
    validate :require_at_least_one_push_category 
    def require_at_least_one_push_category 
     if push_category_ids.empty? && push_categories.size < 1 
      errors.add(:push_category_ids, I18n.t("errors.messages.require_at_least_one")) 
     end 
     end 

和我的#POST控制器測試看起來像:

before do 
    @push_provider = FactoryGirl.create(:push_provider) 
    @user = FactoryGirl.create(:user) 
    @push_entry = @push_provider.push_entries.build(FactoryGirl.attributes_for(:push_entry)) 
    @push_category = @push_provider.push_categories.create(FactoryGirl.attributes_for(:push_category)) 
    @push_entry.push_category_ids = [@push_category.id] 
    @push_entry.save 
    end 


describe "POST #create" do 
    context "with valid params" do 
     it "creates a new push entry for push provider" do 
     expect { 
      post :create, commit: "Speichern", push_provider_id: @push_provider.id, push_entry: FactoryGirl.attributes_for(:push_entry, :push_provider_id => @push_provider.id, :push_category_ids => [@push_category.id]) 
     }.to change(PushEntry, :count).by(1) 
     end 
    end 
end 

編輯#1

我強烈參數在push_entries_controller看這

def push_entry_params 
    params.require(:push_entry).permit(:title, :entry_text, :style, :image, :url, :published_at, :offer_price, :event_date, :scheduled_push, :push_category_ids, food_offers_attributes: [:id, :dish, :price, :_destroy]) 
    end 

有什麼建議嗎?

+0

顯示您的控制器。這可能是一個強烈的問題。你是否允許'params.require(X).permit ...'中的'push_category_ids' – AbM

回答

0

我發現自己的問題,我只保存push_category_ids中的一個push_category,所以我不需要在我的測試中的方括號。謝謝你的幫助。