Reloading an object not working in rspec
Solution 1
I solved the problem by switching to FactoryGirl:
@campaign = FactoryGirl.create(:pending_approval_campaign)
@campaign.approved_at.should be(nil)
post :approve, id: @campaign.id.to_s
@campaign.reload
@campaign.approved_at.should_not be(nil)
That works as intended
Solution 2
Two possible places for errors.
object creation. i.e.
@campaign = Campaign.create(valid_attributes)
Your object may not be created correctly. I suggest you to usecreate!
instead ofcreate
in the test so that any error will be thrown.Controller. When controller expect to find the object with an integer id, you feed it a string. That may also be the problem. I suggest you not to convert the id into string. If for GET, you can do that though not necessary. If for POST, converting to string is wrong.
Solution 3
I would run a test to ensure a Campaign
record is actually being created:
@campaign = Campaign.create(valid_attributes)
puts @campaign.id
.reload
is the first place in your code that a nil @campaign
would flag an error (since you can call .to_s
on a nil object)
Eric Baldwin
Updated on September 16, 2022Comments
-
Eric Baldwin over 1 year
I am trying to test a controller method with the following code:
it "should set an approved_at date and email the campaign's client" do @campaign = Campaign.create(valid_attributes) post :approve, id: @campaign.id.to_s @campaign.reload @campaign.approved_at.should_not be(nil) end
However, when I run this test, I get the following error:
Failure/Error: @campaign.reload ActiveRecord::RecordNotFound: Couldn't find Campaign without an ID
When I run the analagous lines in the rails console, the reload works and the value is set as I need it to be. Why isn't reload working for me when I run the code in an rspec test?