0

我的应用程序运行良好,但我无法通过测试。我是rails新手,如果答案很明显,请原谅我。

我需要一个可用于每个视图的变量,所以我在application_controller.rb

class ApplicationController < ActionController::Base
  protect_from_forgery
  before_filter :course
  def course
    @course = Course.find_slug(params[:course])
  end
end

我的测试用例如下所示:

it "creates an attempt" do
  sign_in current_user 
  params = {:id => challenge.id, :description => "this was hard!", :course => "design"}
  @course = FactoryGirl.create(:course)
  post :completed, params
  response.should redirect_to "/#{@course.slug}/?challenge_slug=" + challenge.slug
  Attempt.count.should == 1
  Attempt.last.description.should == params[:description]
end

我的控制器中的方法如下所示:

  def completed
    @challenge = Challenge.find(params[:id])
    @challenge.completed(current_user, params)
    redirect_to "/#{@course.slug}/?challenge_slug=" + @challenge.slug.to_s
  end

如果我使用该应用程序,所有这些都可以正常工作,但测试显示:

  1) ChallengesController completing a challenge creates an attempt
     Failure/Error: post :completed, params
     NoMethodError:
       undefined method `slug' for nil:NilClass
     # ./app/controllers/challenges_controller.rb:16:in `completed'
     # ./spec/controllers/challenges_controller_spec.rb:36:in `block (3 levels) in <top (required)>'

如果我硬编码我的控制器说redirect_to "#{'expected_value'}"然后测试通过,那么在测试环境中我似乎无权访问应用程序变量@course,这是正确的吗?

我不知道如何解决这个问题。任何帮助表示赞赏。

4

1 回答 1

1

一种解决方案是存根 find 方法并返回实例变量。

before(:each) do
  @course = FactoryGirl.create(:course)
  Course.stub(:find_slug).and_return(@course)
end

这使您的测试更加健壮,因为“find_slug”的测试应该在您的课程模型中,而不是控制器中。

于 2012-04-26T06:01:19.173 回答