如何在 rspec 中使用 padrino 辅助方法 [英] how to use padrino helper methods in rspec
问题描述
我正在使用 padrino 和 rspec,我希望能够测试我编写的辅助方法.
I'm using padrino and rspec and I'd like to be able to test a helper method that I wrote.
我有
describe "POST /sessions" do
it "should populate current_user after posting correct user/pass" do
u = User.create({:email=>"john@gmail.com", :password=>"helloworld", :password_confirmation=>"helloworld"})
user = {
email:"john@gmail.com",
password:"hellowolrd"
}
post '/sessions/new', user
current_user.should_not == "null"
end
end
app/controllers/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
app/helpers/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?
So this is really a two-part question. First part is that my method current_user is not even found. Second, I believe if it were found, it might throw errors as to session not being defined. But first things first, why am i getting 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)>'
推荐答案
这是在他们的问题跟踪器中回答的:https://github.com/padrino/padrino-framework/issues/930#issuecomment-8448579
This was answered in their issue tracker: https://github.com/padrino/padrino-framework/issues/930#issuecomment-8448579
从那里剪切和粘贴:
速记助手(顺便说一下,这是 Sinatra,而不是 Padrino 功能)由于某种原因难以测试:
Shorthand helpers (this is a Sinatra, not a Padrino feature, by the way) are hard to test for a reason:
MyApp.helpers do
def foo
end
end
是以下的简写:
helpers = Module.new do
def foo
end
end
MyApp.helpers helpers
所以可测试性的问题很明显:助手是一个匿名模块,很难引用匿名的东西.解决方案很简单:使模块显式:
So the problem for testability is obvious: the helpers are an anonymous module and its hard to reference something that is anonymous. The solution is easy: make the module explicit:
module MyHelpers
def foo
end
end
MyApp.helpers MyHelpers
然后以您想要的任何方式对其进行测试,例如:
and then test it in any fashion you want, for example:
describe MyHelpers do
subject do
Class.new { include MyHelpers }
end
it "should foo" do
subject.new.foo.should == nil
end
end
此外,您的示例不起作用,因为它假定助手是全局的,而它们不是:它们受应用程序的限制.
Also, your example doesn't work because it assumes that helpers are global, which they are not: they are scoped by application.
这篇关于如何在 rspec 中使用 padrino 辅助方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!