Rails 4在rspec中路由以测试PATCH

时间:2013-12-04 07:04:42

标签: ruby-on-rails rspec ruby-on-rails-4

这是我的routes.rb

resources :agreements, param: :customer_number, only: :show, as: 'agreement_from_customer_number'

resources :agreements, only: [:index, :update] do
   resources :orders, only: :index
end

这是我的AgreementsController

def update
   ...
end

这是我测试更新操作的rspec测试:

before :each do
  @agreement = create :agreement
end

it 'updates the correct agreement through the internal API' do
    patch agreement_path(@agreement)
end

我的应用程序使用ActiveModel,因此它没有数据库。因此,create块中的before方法只执行以下操作:

factories/agreement.rb

factory :agreement do
  skip_create
  id '1'
  customer_number '1001'
  agreement_id '101'
  return_address 'Fakeville, USA'
  return_postal_code '2013'
end

测试返回以下错误:

ActionController::UrlGenerationError:
   No route matches {:id=>#<Agreement:0x007f94ab7b0ce0 @id="1", @agreement_id="101", @customer_number="1001", @return_address="Fakeville, USA", @return_postal_code="2013">} missing required keys: [:id]

如果我将测试改为这样:

it 'updates the correct agreement through the internal API' do
    patch agreement_path(@agreement.id)
end

我收到以下错误:

     ActionController::UrlGenerationError:
   No route matches {:controller=>"agreements", :action=>"/agreements/1"}

帮助: - |

1 个答案:

答案 0 :(得分:0)

我通过执行以下操作解决了这个特殊问题:

patch :update, agreement: @agreement.attributes

因为控制器需要散列值而不是对象文字,所以这很有用: - )