gpt4 book ai didi

ruby-on-rails - 在 Rails 3.1 中使用 rspec 测试嵌套资源 Controller

转载 作者:行者123 更新时间:2023-12-01 14:36:25 24 4
gpt4 key购买 nike

我正在尝试对嵌套资源的 Controller 进行测试。

在routes.rb中嵌套是这样的

resources :cars, :only => [:index, :destroy, :show] do
resources :car_subscriptions, :only => [:new, :create], :as => :follow_subscriptions
end

我正在尝试最具体地测试创建操作:

describe CarSubscriptionsController do

def valid_attributes
{:car_id => '1', :user_id => '2'}
end

describe "POST create" do
describe "with valid params" do
it "creates a new CarSubscription" do
expect {
post :create, :car_id => 1, :car_subscription => valid_attributes
}.to change(CarSubscription, :count).by(1)
end

it "assigns a newly created car_subscription as @car_subscription" do
post :create, :car_subscription => valid_attributes
assigns(:car_subscription).should be_a(CarSubscription)
assigns(:car_subscription).should be_persisted
end

it "redirects to the created car_subscription" do
post :create, :car_subscription => valid_attributes
response.should redirect_to(CarSubscription.last)
end
end
end

end

其实是rails脚本生成的脚手架的一部分。而且我只修改了valid_attributes和第一个'it'中的post

输出是这样的:

  1) CarSubscriptionsController POST create with valid params creates a new CarSubscription
Failure/Error: post :create, :car_id => 1, :car_subscription => valid_attributes
ActionController::RoutingError:
No route matches {:car_id=>"1", :car_subscription=>{:car_id=>"1", :user_id=>"2"}, :controller=>"car_subscriptions", :action=>"create"}
# ./spec/controllers/car_subscriptions_controller_spec.rb:34:in `block (5 levels) in <top (required)>'
# ./spec/controllers/car_subscriptions_controller_spec.rb:33:in `block (4 levels) in <top (required)>'

所有'it's都是一样的错误。

我试过从 routes.rb 文件中删除 :as => :following_subscriptions 但同样的问题。

我实际上已经拆分了 car_subscriptions 的资源,所以 indexdestroy 是非嵌套的,而 createnew 嵌套在 :cars

我不想使用像 answer 中那样的硬编码路径但如果这是唯一的方法,我可以试一试:

{ :post => "/forum_topics/1/forum_sub_topics" }.should route_to(:controller => "forum_sub_topics", :action => "create", :forum_topic_id => 1)

编辑

哦,我的佣金路线是这样的:

car_follow_subscriptions_da POST   /biler/:car_id/car_subscriptions(.:format)                     {:action=>"create", :controller=>"car_subscriptions", :locale=>"da"}

最佳答案

根据 rake routes 提供的内容,我想你应该替换:

 post :create, :car_id => 1, :car_subscription => valid_attributes

与:

 post :create, :car_id => 1, :car_subscription => valid_attributes, :locale => "da"

关于ruby-on-rails - 在 Rails 3.1 中使用 rspec 测试嵌套资源 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8496732/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com