rspec控制器post动作测试因ActiveModel :: ForbiddenAttributesError而失败

时间:2013-08-23 22:55:16

标签: ruby rspec controller factory-bot

我想测试我的控制器的后期操作,但它失败了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以查看是否有错误,但params [:feed]包含有效的哈希值。 我在这里错过了什么吗?

1 个答案:

答案 0 :(得分:4)

是的,你错过了什么。 Rails 4默认启用strong parameters。您需要将其更改为以下内容:

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