,有4类用户:非登录,消费者,生产者和管理员。Rspec,在我的系统中有更好的方式来编写这个
我目前使用的是Cancan for ACL。
在写RSpec的,我看到以下内容:
describe DealsController do
describe "non-signed-in users" do
before(:each) do
@deal = Factory(:deal)
end
describe "should be able to" do
it "access index" do get :index end
it "show deal" do get :show, :id => @deal end
after(:each) do
response.should be_success
end
end
describe "should not be able to" do
it "redeem" do get :redeem end
it "new" do get :new end
it "edit" do get :edit, :id => @deal end
it "update" do get :update, :id => @deal end
it "destroy" do get :destroy, :id => @deal end
after(:each) do
response.should_not be_success
response.should redirect_to(root_path)
flash[:error].should == "Permission denied."
end
end
end
describe "consumers" do
before(:each) do
@user = test_sign_in(Factory(:user, :role => "consumer"))
@deal = Factory(:deal)
end
describe "should be able to" do
it "access index" do get :index end
it "show deal" do get :show, :id => @deal end
after(:each) do
response.should be_success
end
end
describe "should not be able to" do
it "redeem" do get :redeem end
it "new" do get :new end
...
after(:each) do
response.should_not be_success
response.should redirect_to(root_path)
flash[:error].should == "Permission denied."
end
end
end
describe "producer" do
before(:each) do
@user = test_sign_in(Factory(:user, :role => "producer"))
@business = Factory(:business, :user_id => @user.id)
@deal = Factory(:deal, :business_id => @business.id)
end
it "should be able to access index" do
get :index
response.should be_success
end
describe "in show deals" do
it "should be able to see merchant controls for his deal" do
get :show, :id => @deal
response.should have_selector('h3', :content => "Merchant Controls")
end
it "should not be able to see merchant controls for other's deal" do
@user2 = Factory(:user, :role => "producer")
@business2 = Factory(:business, :user_id => @user2.id)
@deal2 = Factory(:deal, :business_id => @business2.id)
get :show, :id => @deal2
response.should_not have_selector('h3', :content => "Merchant Controls")
end
end
describe "should not be able to" do
it "new" do get :new end
...
after(:each) do
response.should_not be_success
response.should redirect_to(root_path)
flash[:error].should == "Permission denied."
end
end
end
end
我还没有填写管理部分,但我非常有信心,这是不推荐的方式去这样做。
什么是更好的方法?
谢谢你的一切!我是rspec和测试新手,这真的很有帮助! – disappearedng
FWIW,我明白,这可能只是发生在我身上,但我发现,对于一个工作与{...}和...工作... end结束,我必须在它之后用括号来解释。即它(“应该做些什么”){...}我使用Rspec 2.13,ruby 2,并且使用spork和guard与dRb进行测试。虽然很好的答案!希望我可以多次赞扬它! :) – engineerDave