Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reloading an object not working in rspec

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?

like image 811
Eric Baldwin Avatar asked Jul 01 '13 00:07

Eric Baldwin


3 Answers

Two possible places for errors.

  1. object creation. i.e.@campaign = Campaign.create(valid_attributes) Your object may not be created correctly. I suggest you to use create! instead of create in the test so that any error will be thrown.

  2. 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.

like image 179
Billy Chan Avatar answered Nov 17 '22 00:11

Billy Chan


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

like image 34
Eric Baldwin Avatar answered Nov 16 '22 23:11

Eric Baldwin


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)

like image 43
Runthral Avatar answered Nov 17 '22 00:11

Runthral