2015-11-23 169 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,所以我不需要在我的测试中的方括号。谢谢你的帮助。