0

I am trying to test my show action, but I first must save an object to the DB for it to show.

test "should get show" do
  post :create, question: { question: 'apple'}
  get :show, {'id' => "1"}
  assert_response :success
  assert_not_nil assigns(:question)
end

In another test, I have the post :create... line and it works. But, here I keep getting ActiveRecord::RecordNotFound: Couldn't find Question with id=1 and so I'm not sure what the issue is. How do I fix this? Big picture what is the best way to do this?

Edit:

I've changed my test to look like this:

test "should get show" do
    post :create, question: {set_id: 4}
    pp Question.all
    get :show, {'id' => "1"}
    assert_response :success
    assert_not_nil assigns(:question)
end

Which gives me:

[#<Question id: 261990764, question: "Who was... updated_at: "2012-06-15 19:34:16">,
 #<Question id: 607888892, question: "Who was... updated_at: "2012-06-15 19:34:16">,
 #<Question id: 607888893, question: nil, ... set_id: 4,...]

Which is what you would expect, except for the ID part. Does rails assign random IDs in the test environment?

Here is my passing test:

test "should get show" do
  q = Question.new(question: 'q', answer: 'a', set_id: 1)
  q.save
  get :show, {id: q.id}
  assert_response :success
  assert_not_nil assigns(:question)
end

Still would love for someone to explain to me why the ID is so high though and how rails assigns it.

And, Here is an example that takes advantage of fixtures:

test "should get show2" do
    get :show, {id: questions(:prez_one).id}
    assert_response :success
    assert_not_nil assigns(:question)
end
Noah Clark
  • 8,101
  • 14
  • 74
  • 116
  • 1
    Hi Noah. Kinda late to get back to you. If you are still wondering how the ID got so high, it's not rails that assigns it. It's sqlite. This also happens to MySQL db, btw. When you delete all records in the table, it doesn't automatically reset the auto-incremented ID to 0. You have to reset it manually. See http://stackoverflow.com/questions/1601697/sqlite-reset-primary-key-field – Ervi B Jul 09 '12 at 17:14
  • @Linx thanks for the update. I figured it out when I was looking through the DB via the SQLight Database Browser. Really appreciate the followup though! – Noah Clark Jul 09 '12 at 19:57

1 Answers1

1

Have you checked if the Question you created has id = 1?
Is the id column auto-incremented in your db?
Are you using MySQL db?

You might want to show all Questions after the post :create line.
Then, select the Question with apple to get the corresponding id.

Hope that helps.

Ervi B
  • 770
  • 7
  • 16
  • I'm using SQLite. As long as there is a single question created, then it should have ID = 1, because it is auto-incremented. How would I show all questions? I assume `q_holder = Question.all` would get them all, but how would I print them out in the test? – Noah Clark Jun 15 '12 at 19:30