I have worked this week on testing my controller for my Rails application, and I found something interesting about strong parameters and my results, of course I would like to dig deeper and learn more about why this difference shows in my tests.
First I wanted to create a test for my POST method on one of my controllers so I wrote this first test:
let(:meeting) { create(:meetings_list) }
....
describe 'POST #create' do
context 'when user is registered' do
login_user
it 'should save the new meeting list with proper attributes' do
expect do
post(:create, params: { meetings_list: {
title: meeting.title,
responsible: meeting.responsible
} })
end.to change { MeetingsList.count }.by(2)
end
When I first wrote it I used the count change by 1 on the last line and it failed, the test indicated 2 was the final count, which I did not understood why. So I went back to my factory and checked:
FactoryBot.define do
factory :meetings_list do
title { Faker::Team.name }
responsible { Faker::TvShows::SouthPark.character }
end
factory :invalid_meeting, parent: :meetings_list do
title { nil }
end
factory :meetings_item do
meetings_list
date { 'Date of Today' }
reason { 'Spende' }
amount { 22 }
end
end
So this lead me to write the test with another method included in factorybot, attributes_for
, which became helpful and less code was also written. I am not sure if this is more o less explicit but It worked so far. I would like to have some feedback, since tests are supposed to be explicit and simple to read or at least that is what I am aiming for.
describe 'POST #create' do
context 'when user is registered' do
login_user
it 'should save the new meeting list with proper attributes' do
expect do
post(:create, params: { meetings_list:
FactoryBot.attributes_for(:meetings_list)})
end.to change { MeetingsList.count }.by(1)
end
Now it passes to green, only one "meeting_list" was created and the test pass with success. What was making the two "meetings_list" to be created before?