2012-07-02 40 views
2

我正在使用padrino和rspec,我希望能夠測試我編寫的幫助程序方法。如何在rspec中使用padrino幫助程序方法

規格/應用/控制器/ sessions_controller_spec.rb

describe "POST /sessions" do 
    it "should populate current_user after posting correct user/pass" do 

     u = User.create({:email=>"[email protected]", :password=>"helloworld", :password_confirmation=>"helloworld"}) 

     user = { 
     email:"[email protected]", 
     password:"hellowolrd" 
     } 
     post '/sessions/new', user 
     current_user.should_not == "null" 
    end 
    end 

應用程序/控制器/ sessions_controller.rb

post "/new" do 
    user = User.authenticate(params[:email], params[:password]) 
    if user 
     session[:user_id] = user.id 
     redirect '/' 
    else 
     render "sessions/new" 
    end 
    end 

應用程序/傭工/ sessions_helper.rb

Testing.helpers do 
    def current_user 
    @current_user ||= User.find(:id=>session[:user_id]) if session[:user_id] 
    end 
end 

所以這是一個真正的兩部分問題。第一部分是我的方法current_user甚至沒有找到。其次,我相信如果找到它,它可能會引發錯誤,因爲未定義會話。但首先,我爲什麼要獲取undefined_method current_user?

Failures: 

    1) SessionsController POST /users should populate current_user after posting correct user/pass 
    Failure/Error: current_user.should_not == "null" 
    NameError: 
     undefined local variable or method `current_user' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_2:0x0000000313c0d8> 
    # ./spec/app/controllers/sessions_controller_spec.rb:20:in `block (3 levels) in <top (required)>' 

回答

4

這是回答了他們的問題跟蹤:https://github.com/padrino/padrino-framework/issues/930#issuecomment-8448579

剪切,並從那裏粘貼:

速記傭工(這是一個西納特拉,不是Padrino功能,方式)是很難測試的一個原因:

MyApp.helpers do 
    def foo 

    end 
end 

是簡寫:

helpers = Module.new do 
    def foo 
    end 
end 

MyApp.helpers helpers 

所以可測試性的問題是顯而易見的:助手是一個匿名模塊,它很難引用匿名的東西。解決辦法很簡單:使模塊明確:

module MyHelpers 
    def foo 
    end 
end 

MyApp.helpers MyHelpers 

,然後在任何你想要的方式進行測試,例如:

describe MyHelpers do 
    subject do 
    Class.new { include MyHelpers } 
    end 

    it "should foo" do 
    subject.new.foo.should == nil 
    end 
end 

而且,你的例子不工作,因爲它假定幫手是全球性的,他們不是:他們的範圍是應用程序。

相關問題