应用程序变量在测试环境中为零

时间:2012-04-26 05:36:24

标签: ruby-on-rails rspec

我的应用程序工作正常,但我无法通过测试。如果答案显而易见的话,我是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,这是正确的吗?

我迷失了如何解决这个问题。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

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

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

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