Noah Clark
Noah Clark

Reputation: 8131

Why Does Rails Function Test Fail When I try to Save Object To DB

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

Upvotes: 0

Views: 168

Answers (1)

Ervi B
Ervi B

Reputation: 800

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.

Upvotes: 1

Related Questions