问题
I have on view show.html.erb
<%= @question.user.lesson_id %>
and this is on browser a number.
my questions_controller.rb is
def show
@question = Question.find(params[:id])
@comments = @question.comments.all
if user_signed_in?
@rating_currentuser = @question.ratings.find_by_user_id(current_user.id)
unless @rating_currentuser
@rating_currentuser = current_user.ratings.new
end
end
and my questions_controller_test.rb
test "should show question signed in" do
sign_in users(:user2)
get :show, :id => @question_user1.to_param
assert_response :success
end
and everything is ok (browser and testing)
when change view show.html.erb
<%= @question.user.lesson.name %>
I am OK with browser but fail testing with
ActionView::Template::Error: undefined method `name' for nil:NilClass.
I try this
@name = Lesson.find(params[:id])
on questions_controller.rb then test fail with
Expected response to be a <:success>, but was <302>
similar questions here here and here
回答1:
Using try can potentially mask the underlying problem.
For example, when I had this error it was because I wasn't creating a model object without the correct foreign key references fixed up - the view was rendering using the FK association with the name attribute - e.g. Product.ProductType.name. If I had used try to workaround it, it would have masked this fault in my test which would have been undesirable in the test. Once I had added the correct references everything worked as it should have with no need for try(:name).
回答2:
The solution from this answer
is use the try method and change view as
<%= @question.user.lesson.try(:name) %>
来源:https://stackoverflow.com/questions/10840783/test-fail-with-actionviewtemplateerror-undefined-method-name-for-nilnilc