So I have something like this in Rails with rspec:
it "should create a new user" do
lambda do
post :create, @attr
end.should change(User,:count)
end
But the post :create, @attr creates both a User and a Company, so how do I "chain" the change calls so that i can test both?
What Im looking for is something like end.should change(User,:count) && change(Company,:count)
I'd argue you're trying to assert to much in a single test and it doesn't match the name of the test. Consider this instead:
it "should create a new user" do
lambda do
post :create, @attr
end.should change(User,:count)
end
it "should create a new company" do
lambda do
post :create, @attr
end.should change(Company,:count)
end
Also, you may not be aware that there's a nicer way of writing those assertions which does the same thing, but reads much more nicely:
expect {
post :create, @attr
}.to change(Company, :count)
After growing as a developer for a couple of years, I have found quite a clean solution for testing multiple values when needed:
expect{ execute }.to change{ [spe1.reload.trashed?, spe2.reload.trashed?] }.from([true, true]).to([false, false])
But when we do need to test creation of multiple records:
[User, Company].each do |klass|
it "creates one #{klass}" do
expect{ post :create, valid_args }.to change(klass, :count).by(1)
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With