How to test strong params with Rspec?

后端 未结 4 1269
夕颜
夕颜 2021-02-13 15:40

What is the actual strategy to test strong params filtering in Rails controller with Rspec? (Except shoulda matchers) How to write failing test and then make it green?

4条回答
  •  猫巷女王i
    2021-02-13 16:07

    Create 2 hashes with expected and all (with unsatisfied) parameters. Then pass all params to action and check that you object model receiving only expected params. It will not if you are not using strong parameter filters. Than add permissions to params and check test again.

    For example, this:

    # 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
    

    will pass all params to User and test will fail. And when you filter them:

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

    and change action with User.create(user_params), test will pass.

提交回复
热议问题