RSpec不会将Hash字段返回给Controller

时间:2015-01-08 20:13:43

标签: ruby-on-rails hash rspec

所以我在我的Rails API中运行了#create测试,但不知何故,Factory中的一个Hash字段没有到达Controller的INSERT。

    factory :child do
        id 5
        type "type1"
        vars { var1: 1, var2: 2 }
        values { value1: 1, value2: 2 }
    end

测试

    it "creates child with associated id" do
        Rails::logger.info "Testing CREATE"
        child = FactoryGirl.build(:child).attributes
        Rails::logger.info "INITIAL:"
        Rails::logger.info child
        post :create, :parent => @parent_id, :child => child
        expect(response).to have_http_status(201)
    end

控制器操作

def create
    @parent = Parent.find(params[:parent_id])
    @child = @parent.childs.build(child_params)

    if @child.save
      render json: @child, status: 201
    else
      render json: { error: "404: Not Found" }.to_json, status: 404 #just to know, this error will be changed
    end
end

(...) some code here

def child_params
  params.require(:child).permit(:id, :type, :parent_id) #here I've also tried to include :vars, :value unsuccessfully
end

结果

D, [2015-01-08T20:02:19.016182 #76314] DEBUG -- :   SQL (0.9ms)  
INSERT INTO "childs" ("id", "type", "parent_id", "created_at", "updated_at") 
VALUES ($1, $2, $3, $4, $5) RETURNING "id"  
[["id", 1], ["type", "type1"], ["parent_id", 1], ["created_at", "2015-01-08 20:02:19.010801"], ["updated_at", "2015-01-08 20:02:19.010801"]]

如您所见,Controller不会读取变量和值哈希值。 RSpec测试读得很好:

I, [2015-01-08T20:02:18.989104 #76314]  INFO -- : 
{"id"=>1, "type"=>"type1", "vars"=>{"var1"=>"1", "var2"=>"2"}, "values"=>{"value1"=>"1", "value2"=>"2"}, "created_at"=>nil, "updated_at"=>nil, "parent_id"=>nil}

我错过了什么吗?

1 个答案:

答案 0 :(得分:1)

目前strong_params不允许(AFAIK和according to this)允许内部使用未知键的哈希值,因此如果您知道键,则需要使用强大的参数进行操作

def child_params
  params.require(:sth).permit(:id, :type, :parent_id, vars: [:var1, :var2], values: [:value1, :value2]) 
end

或只是做

def child_params
  params.require(:sth).permit!
end

这是我的控制台的现场直播

[7] pry(#<Admin::SampleController>)> params.require(:sth).permit(:type, vars: [:var1, :var2])
Unpermitted parameters: id, values, created_at, updated_at, parent_id
=> {"type"=>"type1", "vars"=>{"var1"=>"1", "var2"=>"2"}}
[8] pry(#<Admin::SampleController>)> params.require(:sth).permit(:type, vars: [[]])
Unpermitted parameters: var1, var2
Unpermitted parameters: id, values, created_at, updated_at, parent_id
=> {"type"=>"type1", "vars"=>{}}
[9] pry(#<Admin::SampleController>)> params.require(:sth).permit!
=> {"id"=>1,
 "type"=>"type1",
 "vars"=>{"var1"=>"1", "var2"=>"2"},
 "values"=>{"value1"=>"1", "value2"=>"2"},
 "created_at"=>nil,
 "updated_at"=>nil,
 "parent_id"=>nil}