为什么我的功能测试失败了?

时间:2012-02-04 21:36:11

标签: ruby-on-rails

提前道歉,对铁路来说相当新。创建一个展示烹饪食谱的网站,我对我的主页和我的食谱页面进行了功能测试,两者都失败了。他们过去常常通过,然后我做了“某事”,现在他们失败了。看起来测试无法以某种方式加载灯具。

专注于配方资源中的“应该显示”测试,失败的测试就在这里;

class RecipesControllerTest < ActionController::TestCase
  setup do 
    @recipe = recipes(:spag_bol)
  end

  test "should get show" do
    get :show, :id => @recipe.to_param

    assert_not_nil assigns(:recipe)
    assert_equal @recipe.name, assigns(:page_title)
    assert_tag :h1, :content => assigns(:page_title)
    assert_tag :p, :content => @recipe.excerpt

    assert_tag :h2, :content => "Ingredients"
    assert_select "#ingredients li", @recipe.ingredients.lines.count

    assert_tag :h2, :content => "Method"
    assert_select "#method li", @recipe.method.lines.count

    assert_template :show
    assert_response :success
  end
end

此测试的夹具在这里;

spag_bol:
  id: 1
  name: "Spaghetti Bolognaise"
  excerpt: "Test test test."
  serves: "2"
  preparation_time: "30 minutes"
  cooking_time: "1 hour"
  method: "Test test test\ntest test test."
  ingredients: "Test test test\ntest test test."

失败实际上并不是失败,这是一个错误;

RecipesControllerTest:
    ERROR should get show (0.02s) 
          ActionView::Template::Error: undefined method `name' for nil:NilClass
          /Users/Laura/.rvm/gems/ruby-1.9.2-p290/gems/activesupport-3.1.3/lib/active_support/whiny_nil.rb:48:in `method_missing'

看起来非常像测试没有加载夹具 - 任何人都可以告诉我为什么?

编辑(解决方案说明)

而不是实际代码,我曾经只是链接到我上面的git repo。正如Ryan在下面指出的那样,如果我链接到主分支,那么如果他们发现这个问题就会在几周内对某人没有好处,所以这些链接已经消失并且已被代码替换。具有讽刺意味的是,这样做可以说明我出错的地方!我确信测试中的下一行导致了问题;

assert_equal @recipe.name, assigns(:page_title)

因为那是唯一一个引用“名称”方法的人,并且错误消息非常使得它看起来像夹具没有带回一个配方。事实上,它是,并且我的索引页实际上抛出了REAL错误,因为CATEGORY没有名称。当我实际运行应用程序时没有发生这种情况,因为我的开发环境已经填写了所有这些数据,这进一步使我确信问题出在测试而不是代码上。

所以,经验教训:如果你的功能测试看起来没有问题,那么你的控制器或视图可能会因为某些其他原因而抛出错误,这与你试图测试的内容无关。

2 个答案:

答案 0 :(得分:2)

这里的问题是你的食谱夹具没有设置任何类别。当它尝试呈现app/views/recipes/show.html.erb时,会调用comma_separated_links_for方法,该方法假定已填充@recipe.categories

在此方法中,它在其上调用pop,它获取此数组中的最新元素。由于没有类别,因此返回nil

稍后,在此方法的第10行附近,您尝试在name上致电nil,这会导致您的测试失败。

要解决此问题,请为配方夹具指定一个类别。我很长时间没有使用灯具,所以我无法就如何做到这一点提出建议。我使用factory_girl之类的东西。

答案 1 :(得分:1)

您的测试运行正常。您的应用程序代码失败,因为它试图在nil上调用方法。这通常发生在控制器逻辑错误或模​​板拼写错误中。在您的情况下,您假设您在recipes#show的第一行找到了有效记录,因此您继续使用,但是您没有在测试中传递有效的ID。

tl;博士:我想这个:

test "should get show" do
  get :show, :id => @recipe.to_param

应该是这样的:

test "should get show" do
  get :show, :id => @recipe.id

但我认为测试告诉你可能存在需要解决的更大问题......

相关问题