d11*_*wtq 9 ruby rspec ruby-on-rails rspec2
我试图通过创建一个共享示例组来保持我的规范DRY,该组对所有管理控制器(Admin我项目命名空间下的所有控制器)执行样板检查.我正在努力弄清楚如何去做,因为共享示例需要提供有关使用哪些操作和参数的信息.如果测试失败,理想情况下应该存在有意义的错误(即包括它正在测试的操作的细节).
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
Run Code Online (Sandbox Code Playgroud)
@actions由于共享示例组不可见的明显原因,此错误.如果我使用let,这仅在示例的上下文中可用,而不是在describe块的上下文中.有任何想法吗?
Dav*_*sky 27
这是一个更清洁的方式应该工作:
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
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参见http://relishapp.com/rspec/rspec-core/v/2-6/dir/example-groups/shared-examples
| 归档时间: |
|
| 查看次数: |
2823 次 |
| 最近记录: |