,有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