0

我正在通過爲現有項目編寫規範來學習RSpec。對於多態資源備註的控制器規範,我遇到了問題。幾乎任何其他模型可以像這樣與Notes的關係:has_many :notes, as: :noteableRSpec:具有多態資源的控制器規範,「無路由匹配」錯誤

此外,該應用程序是多租戶,其中每個帳戶可以有多個用戶。在URL中,每個帳戶都由:slug而不是:id訪問。所以,我的多功能使用租戶,多態路由看起來是這樣的:現在,在新的行動

new_customer_note GET /:slug/customers/:customer_id/notes/new(.:format)  accounts/notes#new 
new_product_note GET /:slug/products/:product_id/notes/new(.:format)  accounts/notes#new 

的測試問題:

# config/routes.rb 
... 

scope ':slug', module: 'accounts' do 

    ... 

    resources :customers do 
    resources :notes 
    end 

    resources :products do 
    resources :notes 
    end 
end 

這導致路線是這樣的。首先,這裏的我如何測試其它非多態性控制器,就像invitations_controller一個例子:

# from spec/controllers/accounts/invitation_controller_spec.rb 
require 'rails_helper' 

describe Accounts::InvitationsController do 
    describe 'creating and sending invitation' do 
    before :each do 
     @owner = create(:user) 
     sign_in @owner 
     @account = create(:account, owner: @owner) 
    end 

    describe 'GET #new' do 
     it "assigns a new Invitation to @invitation" do 
     get :new, slug: @account.slug 
     expect(assigns(:invitation)).to be_a_new(Invitation) 
     end 
    end 
    ... 
end 

當我嘗試使用類似的方法來測試多態性notes_controller,我感到困惑:-)

# from spec/controllers/accounts/notes_controller_spec.rb 

require 'rails_helper' 

describe Accounts::NotesController do 
    before :each do 
    @owner = create(:user) 
    sign_in @owner 
    @account = create(:account, owner: @owner) 
    @noteable = create(:customer, account: @account) 
    end 

    describe 'GET #new' do 
    it 'assigns a new note to @note for the noteable object' do 
     get :new, slug: @account.slug, noteable: @noteable  # no idea how to fix this :-) 
     expect(:note).to be_a_new(:note) 
    end 
    end 
end 

在這裏,我只是在前面的塊中創建一個Customer作爲@noteable,但它也可以是一個產品。當我運行rspec的,我得到這個錯誤:

No route matches {:action=>"new", :controller=>"accounts/notes", :noteable=>"1", :slug=>"nicolaswisozk"} 

我看到的問題是什麼,但我只是無法弄清楚如何處理URL的動態部分,像/products//customers/

任何幫助理解:-)

UPDATE:

改變了get :new線的要求以下

get :new, slug: @account.slug, customer_id: @noteable 

,這將導致錯誤

Failure/Error: expect(:note).to be_a_new(:note) 

TypeError: 
    class or module required 
# ./spec/controllers/accounts/notes_controller_spec.rb:16:in `block (3 levels) in <top (required)>' 

第16行c是:

expect(:note).to be_a_new(:note) 

難道這是因爲:在我的notes_controller.rb新的行動不只是一個@note = Note.new,但初始化一個新的註釋上@noteable,這樣?:

def new 
    @noteable = find_noteable 
    @note = @noteable.notes.new 
end 

回答

2

那麼這裏的問題應該是在這條線

get :new, slug: @account.slug, noteable: @noteable 

你逝去的:noteable在PARAMS。但是,您需要傳遞url的所有動態部分,以幫助軌道匹配路線。在這裏你需要通過參數:customer_id。像這樣,

get :new, slug: @account.slug, customer_id: @noteable.id 

請讓我知道這是否有幫助。

+0

謝謝,看起來像你在做什麼。路由錯誤消失了,但現在它說'TypeError:class or module required'。我想它是指客戶類。我如何在測試中包含這些內容? – GreyEyes

+0

你能給出一些堆棧跟蹤的錯誤嗎?這應該有所幫助。 –

+0

將其包括在內以獲得更好的格式。 –