如何编写一个 RSpec 控制器宏来接受由 let 或 before 块定义的参数?
我使用 Rails 3 和 RSpec 2.6.0。
不确定这是否可能,但这就是我想做的:
describe UsersController do
let(:user) { Fabricate :user }
describe "GET /user/:id" do
should_return_401_code_if_user_is_not_confirmed :get, :show, :id => user.id
end
describe "PUT /user/:id" do
should_return_401_code_if_user_is_not_confirmed :put, :update, :id => user.id
end
end
我尝试像这样实现宏:
module ControllerMacros
def should_return_401_code_if_user_is_not_confirmed(verb, action, params = {})
it "returns a 401 code if the user is not an admin" do
send verb, action, params
response.code.should == "401"
end
end
end
但是在运行这些规范时,我收到错误未定义的局部变量或方法“用户”
。我尝试切换到 before 块中定义的 @user 变量,但它也不起作用。我怀疑这是因为我不在示例块中。
是否可以传递给由 let 或 before 块定义的控制器宏参数?
谢谢!
I use Rails 3 and RSpec 2.6.0.
Not sure if that's possible, but here is what I would like to do:
describe UsersController do
let(:user) { Fabricate :user }
describe "GET /user/:id" do
should_return_401_code_if_user_is_not_confirmed :get, :show, :id => user.id
end
describe "PUT /user/:id" do
should_return_401_code_if_user_is_not_confirmed :put, :update, :id => user.id
end
end
I tried to implement the macro like this:
module ControllerMacros
def should_return_401_code_if_user_is_not_confirmed(verb, action, params = {})
it "returns a 401 code if the user is not an admin" do
send verb, action, params
response.code.should == "401"
end
end
end
But when running those specs I get the error undefined local variable or method 'user'
. I tried to switch to a @user variable defined in a before block, but it does not work either. I suspect it's because I'm not in a example block.
Is it possible to pass to a controller macro arguments defined by let or in a before block?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通过阅读 rspec-users listserve 上的此帖子,答案似乎是否定的。问题是,直到宏主体中的
it
块之前,您的 let/before 变量才会被初始化,因此您无法将它们作为宏调用的参数引用。我正在尝试在我正在开发的网站上做同样的事情。我要采用的解决方案是使用一个块调用宏方法,该块将返回您想要的参数哈希,然后在宏主体中使用
instance_eval
来使用宏的范围来评估该块。From reading through this thread on the rspec-users listserve, it appears the answer is no. The issue is that your let/before vars aren't being initialized until the
it
block in the body of your macro, so you can't reference them as parameters to the macro call.I'm trying to do essentially the same thing in a site I'm working on. The solution I'm going with is to call the macro method with a block that will return the params hash you want, and then use
instance_eval
in the macro body to evaluate the block using the macro's scope.