Rspec强参数剥离参数

时间:2014-04-17 21:02:30

标签: ruby-on-rails rspec strong-parameters

我在模型创建中失败了一个非空条件,谢谢,我认为,强大的参数可以从我的参数散列中删除。

Rspec代码:

it "creates a new Provider" do
    expect {
      post :create, {:admin_provider => {:name => "foo bar"}}, valid_session
    }.to change(Provider, :count).by(1)
end

控制器代码:

def create
  @admin_provider = Provider.new(okay_params)

  respond_to do |format|
    ...Render Views
  end
end

def okay_params
  params.permit(:admin_provider).permit(:name)
end

输出:

Admin::ProvidersController POST create with valid params creates a new Provider
 Failure/Error: post :create, {:admin_provider => {:name => "foo bar"}}, valid_session
 ActiveRecord::StatementInvalid:
   PG::NotNullViolation: ERROR:  null value in column "name" violates not-null constraint
   DETAIL:  Failing row contains (225, null, null, null, t, null, null, null, null, null, null, null, null).
   : INSERT INTO "providers" DEFAULT VALUES RETURNING "id"

我的params发生了什么事情,剥夺了"名称"参数?我已尝试将其作为符号和字符串。我已经尝试过它作为一个let块而不是硬编码。没有不同。每次它似乎都在剥离我的参数。我错过了什么?

1 个答案:

答案 0 :(得分:0)

将您的okay_params定义更新为:

# app/controllers/providers_controller.rb

def okay_params
  params.require(:admin_provider).permit(:name)
end

然后你的规格:

it "creates a new Provider" do
    expect {
      post :create, {:admin_provider => {:name => "foo bar"}}, valid_session
    }.to change(Provider, :count).by(1)
end