我的应用程序运行良好,但我无法通过测试。我是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
,这是正确的吗?
我不知道如何解决这个问题。任何帮助表示赞赏。