How to test strong params with Rspec?

Molfar picture Molfar · Jun 18, 2014 · Viewed 11.2k times · Source

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?

Answer

zishe picture zishe · Jun 18, 2014

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.