如何用Rspec测试强对数?

时间:2014-06-18 17:58:16

标签: ruby-on-rails ruby ruby-on-rails-4 rspec rspec-rails

使用Rspec在Rails控制器中测试强params过滤的实际策略是什么? (除了应该匹配)如何编写失败的测试,然后将其设为绿色?

4 个答案:

答案 0 :(得分:12)

创建2个具有预期和所有(未满足)参数的哈希值。然后将所有参数传递给动作并检查您是否只接收预期参数的模型。如果您没有使用强参数过滤器,则不会。然后为params添加权限并再次检查测试。

例如,这个:

# action
def create
  User.create(params)
end

# spec
it 'creates a user' do
  expect_any_instance_of(User).to receive(:create).
    with({name: 'Sideshow Bob'}.with_indifferent_access)
  post :create, user: 
    { first_name: 'Sideshow', last_name: 'Bob', name: 'Sideshow Bob' }
end

会将所有参数传递给用户,测试将失败。当你过滤它们时:

def user_params
  params.require(:user).permit(:name)
end

并使用User.create(user_params)更改操作,测试将通过。

答案 1 :(得分:9)

我个人使用来自thinkbot的shoulda-matcher

有类似的东西:

it do
  should permit(:first_name, :last_name, :email, :password).
    for(:update, params: params)
end

答案 2 :(得分:3)

我是这样做的:

  describe 'Safe Params' do

   let(:mixed_params) {
     {
       blueprint_application_environment: {
         id: 1000,
         blueprint_id:   1,
         application_id: 2,
         environment_id: 3
       },
       format: :json
     }
   }

context "when processing a Post request with a mix of permitted and unpermitted parameters" do
   before { post :create, mixed_params }

  it "a create will not set the value of the unpermitted parameter" do
     expect(JSON.parse(response.body)["id"]).not_to eq(1000)
   end

  it "a create will set the value of the permitted parameters" do
     expect(JSON.parse(response.body)["blueprint_id"]).to eq(1)
     expect(JSON.parse(response.body)["application_id"]).to eq(2)
     expect(JSON.parse(response.body)["environment_id"]).to eq(3)
   end
 end

控制器代码:

  def create
    @blueprint_application_environment = BlueprintApplicationEnvironment.new(blueprint_application_environment_params)
    if @blueprint_application_environment.save
      render 'show.json.jbuilder'
    else
      render json: @blueprint_application_environment.errors, status: :unprocessable_entity
    end
  end

def blueprint_application_environment_params
    params.require(:blueprint_application_environment).permit(:blueprint_id, :application_id, :environment_id)
end

答案 3 :(得分:1)

就像你使用强参数创建或更新对象一样,它也是类似的,除了正常你喜欢的一件事:

  

post:create,book_id:@ book.id

但是在强参数中你必须这样做:

  

发布:创建,{book_id:@ book.id,评论:{user_id:101,book_id:   @ book.id,说明:"值得购买"} }

你必须传入嵌套参数。