Search code examples
ruby-on-railsunit-testingruby-on-rails-5minitestfinder

In minitest, how do I lookup an item from the database (as opposed to the fixtures definition)?


I'm using Rails 5 and minitest. In minitest, how do I lookup an object from the database by one of its attributes (e.g. not the fixtures designation for the object). In my test I have

item = items(:one)
,,, do some db manipulation to this object ...
Item.all.each do |i|
  puts "#{i.inspect}"
end
updated_item = Item.find(id: item.id)

But the line

updated_Item = Item.find(id: item.id)

dies with the error

ActiveRecord::RecordNotFound: Couldn't find Item with 'id'={:id=>980190962}

What is odd is taht in the lines above, where I print out the records in my database, I can see the object in question with the ID that Rails claims not to find ...

#<Item id: 298486374, name: "MyString", rating: 0, score: 0, created_at: "2018-01-19 20:25:05", updated_at: "2018-01-19 20:25:05">
#<Item id: 980190962, name: "Item1", rating: 1, score: 5, created_at: "2018-01-19 20:25:05", updated_at: "2018-01-19 20:25:05">

What am I doing wrong? How do I lookup the updated object?


Solution

  • find() looks by id , no need to tell, so:

    updated_Item = Item.find(item.id)