2013-02-16 44 views
1

我试图让下面的工作:Rspec NameError,我该如何重构此代码并正确使用路由助手?

#spec/features/senseis_spec.rb 
require 'spec_helper' 

describe "Senseis" do 
    subject { page } 
    @paths = [senseis_path, new_sensei_path, edit_sensei_path(1), sensei_path(1)] 

    describe "sensei can not access" do 
    before { login_as_sensei } 

    @paths.each do |path| 
     describe "#{path}" do 
     before { visit path } 
     it { should have_selector(error, text: "You are not authorized") } 
     end 
    end 
    end 

end 

但它给我一个错误NameError: undefined local variable or method 'senseis_path'

我尝试添加config.include Rails.application.routes.url_helpers该规范帮手,但它并没有帮助。

长的方式工作:

describe "sensei can not access" do 
    before { login_as_sensei } 

    describe "senseis#index" do 
    before { visit senseis_path } 
    it { should have_selector(error, text: "You are not authorized") } 
    end 
end 

理想情况下,我想在另一个文件中定义这个,然后就打电话deny_access_to(path_one, path_two, ...)

附:其他地方定义为error

路线:

    root  /       dashboard#index 
       senseis GET /senseis(.:format)   senseis#index 
         POST /senseis(.:format)   senseis#create 
      new_sensei GET /senseis/new(.:format)  senseis#new 
      edit_sensei GET /senseis/:id/edit(.:format) senseis#edit 
       sensei GET /senseis/:id(.:format)  senseis#show 
         PUT /senseis/:id(.:format)  senseis#update 
         DELETE /senseis/:id(.:format)  senseis#destroy 
    new_sensei_session GET /user/sign_in(.:format)  devise/sessions#new 
     sensei_session POST /user/sign_in(.:format)  devise/sessions#create 
destroy_sensei_session DELETE /user/sign_out(.:format)  devise/sessions#destroy 
     sensei_password POST /user/password(.:format)  devise/passwords#create 
    new_sensei_password GET /user/password/new(.:format) devise/passwords#new 
    edit_sensei_password GET /user/password/edit(.:format) devise/passwords#edit 
         PUT /user/password(.:format)  devise/passwords#update 
+0

请运行'rake routes'并向我们显示输出。 – weltschmerz 2013-02-16 11:13:51

+0

嗨查尔斯,我已经添加了路线。 – 2013-02-16 11:15:49

+0

尝试将顶部的第一个描述更改为'描述不带引号的SenseisController do',它应该使可用的路由 – weltschmerz 2013-02-16 11:19:32

回答

2

尝试像

require 'spec_helper' 

describe "Senseis" do 

    def should_deny_access_to(paths) 
    paths.each do |path| 
     login_as_sensei 
     visit path 
     page.should have_selector(error, text: "You are not authorized") 
    end 
    end 

    it { should_deny_access_to [senseis_path, new_sensei_path, edit_sensei_path(1), sensei_path(1)] } 

end 

或者使用共享的例子组。

+0

谢谢!我在最后添加了一个'logout'调用,它可以工作。 – 2013-02-16 12:57:59