Reloading an object not working in rspec

穿精又带淫゛_ 提交于 2019-12-10 12:42:58

问题


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?


回答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




回答2:


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)




回答3:


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.



来源:https://stackoverflow.com/questions/17396159/reloading-an-object-not-working-in-rspec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!