Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test more than one thing after a lambda in rspec?

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)

like image 987
Houen Avatar asked Mar 21 '11 16:03

Houen


2 Answers

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)
like image 169
idlefingers Avatar answered Sep 18 '22 11:09

idlefingers


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
like image 25
Houen Avatar answered Sep 19 '22 11:09

Houen