我有一个非常简单的控制器操作,它使用一个限制调用来加载一个实例变量,如下所示:
def index
@questions = Question.limit(10)
end
我有一个非常简单的功能测试,使用should、test/unit和Mocha。
should 'limit questions returned' do
Question.expects(:limit)
get :index
end
只有当我在测试中放入mock时,我才会出现以下错误。到目前为止,在浏览器和我的所有其他测试中,一切都能正常工作。如果我把mock调用放在对get:index的调用之后,它会像我预期的那样失败。
test: WelcomeController should limit questions returned. (WelcomeControllerTest):ActionView::Template::Error: undefined method `model_name' for NilClass:Class
app/views/welcome/index.html.erb:7:in `_app_views_welcome_index_html_erb__4244593822102250638_70180558144100'
test/functional/welcome_controller_test.rb:14:in `block in <class:WelcomeControllerTest>'
正如我提到的。所有的东西都能通过我的集成测试,我可以在浏览器中看到这一切。我只有在输入"Question.expects(:limit)"行时才会出现错误。我希望这只是我错过的一些愚蠢的事情。如有任何帮助,我们将不胜感激。
我可以通过更改视图代码来解决这个问题:
<%= render @questions %>
<% if @questions.count >= 10 %>
<h3><%= link_to 'See more ->', questions_path %></h3>
<% end %>
到此:
<% if @questions %>
<%= render @questions %>
<% if @questions.count >= 10 %>
<h3><%= link_to 'See more ->', questions_path %></h3>
<% end %>
<% end %>
无论如何,我可能应该有这样的代码,以防我的控制器操作没有返回任何内容。
事实证明,这是我在做的一件愚蠢的事情。