Hi,
I’ve been trying to find an answer for this problem in the last couple
hours, but I think no discussion was about this exact same thing. So
here it
goes, hope someone can help.
I’m trying to spec a view which works correctly on the browser, but that
generates the following error when I run “rake spec:views”.
ActionView::TemplateError in ‘/survey/show should display the “question
4”
heading correctly’
You have a nil object when you didn’t expect it!
The error occurred while evaluating nil.position
On line #1 of app/views/survey/_question_for_candidate.rhtml
1: <div class="question question-<%= question.position %>">
2: <p class="heading">
3: <span class="number"><%= question.position %>.</span>
4: <span class="description"><%= question.description %></span>
RSpec is telling me that the “question” object is nil. I can’t figure it
out
why.
Here’s the spec that generates the error (the “it” block should test
some
tags inside the “response” object):
require File.dirname(FILE) + ‘/…/…/spec_helper’
describe ‘/survey/show’ do
fixtures ‘questions’, ‘alternatives’
before(:each) do
assigns[:configurations] = {:survey_name => ‘Whatever’}
assigns[:questions] = Array.new
assigns[:questions][4] = questions(:faixa_etaria)
@faixa_etaria = questions(:faixa_etaria)
end
it ‘should display the “question 4” heading correctly’ do
render ‘survey/show’
end
end
Here’s the :faixa_etaria Question fixture I’m using:
faixa_etaria:
id: 1
question_type_id: 1
description: ‘Em qual das faixas etárias abaixo você se inclui?’
position: 4
(The description value is in Portuguese).
Here’s the “show” method inside the SurveyController:
def show
@configurations = {}
Configuration.find(:all).each { |c| @configurations[c.name.to_sym] =
c.value }
@questions = {}
Question.find(:all).each { |q| @questions[q.position] = q }
end
Here’s the piece of code inside the “show.rhtml” template that’s calling
the
helper method that will cause that error:
<%= render_question(@questions[4]) %>
Here’s the “render_question” method implementation, inside the
SurveyHelper
class (invoking “render” seems to be the problem, but I don’t know why):
def render_question(question)
render(:partial => ‘question_for_candidate’, :locals => {:question
=>
question})
end
The :locals Hash has :question as a key, and that is the variable that
RSpec
is complaining about inside the partial.
Finally, here’s the “question_for_candidate” partial:
<%= question.position %>. <%= question.description %>
<% for alternative in question.alternatives -%> <%= radio_button 'candidate', "question_#{question.id}", alternative.id%> <%= alternative.description %><% end -%>
I’m not that experienced with Rails nor RSpec, so I’m totally lost about
this problem.