【问题标题】:Rspec: Controller specs for 2 level nested resourcesRspec:2 级嵌套资源的控制器规范
【发布时间】:2013-04-30 08:47:02
【问题描述】:

我的路线.rb

  namespace :magazine do
   resources :pages do
     resources :articles do
       resources :comments
     end
   end
  end

在为 Comments 编写控制器规范时:

describe "GET 'index'" do
    before(:each) do
     @user = FactoryGirl.create(:user)
     @page = FactoryGirl.build(:page)
     @page.creator = @user
     @page.save
     @article = FactoryGirl.create(:article)
     @comment_attributes = FactoryGirl.attributes_for(:comment, :article_id => @article )
   end
it "populates an array of materials" do
  get :index, ??
  #response.should be_success
  assigns(:comments)
end

it "renders the :index view" do
  get :index, ?? 
  response.should render_template("index")
end

end 

知道如何提供页面和文章参考以获取 :index 吗? 如果我给 : 获取 :index, :article_id => @article.id
我得到的错误如下:

 Failure/Error: get :index, :article_id => @article.id
 ActionController::RoutingError:
   No route matches {:article_id =>"3", :controller=>"magazine/comments"}

【问题讨论】:

    标签: ruby-on-rails rspec controller


    【解决方案1】:

    您的路由至少需要两个 ID:评论的父文章和文章的父页面。

    namespace :magazine do
      resources :pages do
        resources :articles do
          resources :comments
        end
      end
    end
    
    # => /magazine/pages/:page_id/articles/:article_id/comments
    

    必须提供所有父 ID,此路由才能正常工作:

    it "renders the :index view" do
      get :index, {:page_id => @page.id, :article_id => @article.id}
      # [UPDATE] As of Rails 5, this becomes:
      # get :index, params: {:page_id => @page.id, :article_id => @article.id}
      response.should render_template("index")
    end
    

    【讨论】:

    • 所以如果我想测试一个否定的情况——page_id 不在请求中——那我该怎么做呢?
    • 这会导致路由错误。 Rails 指南说“资源应该never be nested more than 1 level deep。”
    • @gg_s 它不会导致错误。事实上,如您所见:guides.rubyonrails.org/routing.html#limits-to-nestingRails Guide 说您不应该不这样做,而不是说你不能这样做。
    • @BartlomiejSkwira 这不可能发生。除非 Rails 路由器中存在错误。
    【解决方案2】:

    在 Rails 5 中,params API 发生了变化:

    get :index, params: { page_id: @page.id, article_id: @article.id }
    

    https://relishapp.com/rspec/rspec-rails/v/3-7/docs/request-specs/request-spec#specify-managing-a-widget-with-rails-integration-methods

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多