2

我想测试我的控制器的发布操作,但它以ActiveModel::ForbiddenAttributesError.

需要'spec_helper'

describe HomeController do
  describe "POST #create" do
    context "with valid attributes" do
      it "saves the new feed in the database" do
        expect{
          post :create, feed: FactoryGirl.attributes_for(:valid_feed)
        }.to change(Feed,:count).by(1)
      end
    end
end

工厂:

FactoryGirl.define do
  factory :valid_feed, class: Feed do
    title "CRE"
    address "http://cre.fm/feed/m4a/"
  end
  factory :invalid_feed, parent: :valid_feed do |f|
    f.address nil
  end
end

控制器:

class HomeController < ApplicationController
  def index
  end
  def create
    @feed = Feed.new(params[:feed])
    if @feed.save
      redirect "/"
     else
      render nothing: true
    end
  end
end

我检查了控制器中的参数以查看是否有问题,但 params[:feed] 包含有效的哈希。我在这里错过了什么吗?

4

1 回答 1

4

是的,你错过了一些东西。Rails 4 默认启用强参数。您需要将其更改为以下内容:

class HomeController < ApplicationController

  def index
  end

  def create
    @feed = Feed.new(feed_params)
    if @feed.save
      redirect "/"
     else
      render nothing: true
    end
  end

  private

  def feed_params
    params.require(:feed).permit(:allowed, :elements, :of, :feed)
  end

end
于 2013-08-24T08:56:24.523 回答