Rebooting an object that does not work 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 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 similar lines in the rails console, the reboot works, and the value is set as I need. Why does rebooting work for me when I run the code in the rspec test?

+6
source share
3 answers

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) 

It works as intended

+8
source

I would run a test to create a Campaign record:

 @campaign = Campaign.create(valid_attributes) puts @campaign.id 

.reload is the first place in your code where nil @campaign will @campaign error (since you can call .to_s on the nil object)

+1
source

Two possible places for mistakes.

  • object creation. those. @campaign = Campaign.create(valid_attributes) Your object may not have been created correctly. I suggest you use create! instead of create in the test, so that any error is selected.

  • Controller When the controller expects to find an object with an integer identifier, you will feed it a string. This can also be a problem. I suggest you not convert id to string. If for GET you can do this, although not necessarily. If the conversion to string is incorrect for POST.

+1
source

Source: https://habr.com/ru/post/948437/


All Articles