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?
Here is how I did it:
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
end
Controller code:
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