Question

I'm having an issue with my specs. I'm trying to run a spec that creates and destroys an associated object, but none of my specs are creating or destroying that object. The weird thing is, I can literally copy and paste every line of code (except for the .should) out of each test into the console and the console will run each expectation perfectly, creating and destroying those objects. Here's a sample:

it "should not destroy notification for like on comment" do
  comment = FactoryGirl.create(:comment)
  like = FactoryGirl.create_list(:like, 2, likable: comment)
  like.first.destroy
  note = comment.user.notifications.find_by(notifiable: comment, from_comment: false)
  note.should_not be_nil
end

Only the first like on a specific comment will send a notification to that comment's author. And if a comment only has one like, and that like is destroyed, it will destroy the notification it had originally sent, but it won't destroy the notification if the comment has more than 0 likes at any time.

Is the problem that I'm just not writing scalable code? I know my specs probably aren't perfect, but why is the console getting different results with identical input?

Was it helpful?

Solution

Are you running your rails console in test environment or in development as it defaults to? Different database and environment configurations might be the reason for different behavior, also the note object might already exist in development db at the time you test it manually in console.

Either try running console in test environment:

$ rails c test

or better temporarily put debugger line inside your test code (you will need get 'debugger' gem installed if don't have it already):

it "should not destroy notification for like on comment" do
  comment = FactoryGirl.create(:comment)
  like = FactoryGirl.create_list(:like, 2, likable: comment)
debugger
  like.first.destroy
  note = comment.user.notifications.find_by(notifiable: comment, from_comment: false)
  note.should_not be_nil
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top