Pierre Marchal
Pierre Marchal

Reputation: 55

Best way to sanitize params in controller spec

I use RSpec with FactoryGirl (to build my model) to test a controller in my application and the test fails there :

subject do
  post :create, params: {
    my_model: attributes_for(:my_model,
                             :pictures_for_post_request)
  }, session: { user_id: user.id }
end
it 'return a 200 status response' do
  subject
  expect(response).to have_http_status 200
end

When the test fails it returns an http status code 400 because in my model's validation I check if an attributes of this model is between two integer values and the value passed as param is a string.

But in my controller I parse my params to get proper integers :

private

def sanitize_params
  [my_params_keys].each do |k|
    params[k] = params[k].to_i if params[k].nil?
  end
end

My question is : How to properly sanitize/.to_i my params in this controller spec without rewrite my function in this spec ?

Upvotes: 0

Views: 1501

Answers (1)

Greg Answer
Greg Answer

Reputation: 717

I think it would be best if the model knows how to handle the data rather than relying on the data being formatted the way you expect it. This is the point of model validation. As you can see, based on your test, the params can be anything even though you attempt to sanitize it.

class MyModel
  before_validation :convert_my_attribute_to_integer

  private

  def convert_my_attribute_to_integer
    self.my_attribute = self.my_attribute.to_i
  end
end

This way your model can be used in multiple contexts without you worrying if the input is properly formatted.

Upvotes: 1

Related Questions