gpt4 book ai didi

ruby-on-rails - 在 RSpec 2 中动态生成共享示例?

转载 作者:数据小太阳 更新时间:2023-10-29 06:47:47 24 4
gpt4 key购买 nike

我试图通过创建一个共享示例组来保持我的规范干燥,该示例组对所有管理 Controller (我项目的 Admin 命名空间下的所有 Controller )执行样板检查。我正在努力弄清楚如何去做,因为共享示例需要提供有关要使用的操作和参数的信息。如果测试失败,理想情况下它应该显示有意义的错误(即包括它正在测试的操作的详细信息)。

require 'spec_helper'

shared_examples "an admin controller" do

before(:each) do
@non_admin = User.make
@admin = User.make(:admin)
end

context "as an admin user" do
@actions.each do |action, params|

specify "I should be able to access ##{action.last} via #{action.first}" do
self.active_user = @admin
send(action.first, action.last, params)

response.status.should be_ok
end

end
end

context "as a regular user" do
@actions.each do |action, params|

specify "I should be denied access to ##{action.last}" do
self.active_user = @non_admin
send(action.first, action.last, params)

response.status.should be 403
end

end
end

end

describe Admin::UserNotesController do

@user = User.make
@actions = { [:get, :index] => { :user_id => @user.id },
[:get, :new] => { :user_id => @user.id },
[:post, :create] => { :user_id => @user.id } }

it_behaves_like "an admin controller"

end

此错误的明显原因是 @actions 对共享示例组不可见。如果我使用 let,这仅适用于示例的上下文,而不适用于 describe block 的上下文。有什么想法吗?

最佳答案

这里有一个更简洁的方法:

require 'spec_helper'

shared_examples "an admin controller" do |actions|
context "as an admin user" do
actions.each_pair do |action, verb|
specify "I should be able to access ##{action} via #{verb}" do
send(verb, action, :user_id => User.make(:admin).id)
response.status.should be_ok
end
end
end

context "as a regular user" do
actions.each_pair do |action, verb|
specify "I should be denied access to ##{action}" do
send(verb, action, :user_id => User.make.id)
response.status.should be 403
end
end
end
end

describe Admin::UserNotesController do
it_behaves_like "an admin controller", {
:index => :get,
:new => :get,
:create => :post
}
end

参见 http://relishapp.com/rspec/rspec-core/v/2-6/dir/example-groups/shared-examples了解更多信息

关于ruby-on-rails - 在 RSpec 2 中动态生成共享示例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6152359/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com