Ruby on rails 用RSpec测试嵌套控制器动作
我设置了如下路线:Ruby on rails 用RSpec测试嵌套控制器动作,ruby-on-rails,unit-testing,rspec,Ruby On Rails,Unit Testing,Rspec,我设置了如下路线: match '/things/:thing_id' => "descriptions#index", :as => :thing resources :things, :except => [:show] do ... resources :descriptions, :only => [:create, :index] end 如何测试嵌套描述的:create方法 到目前为止,我已经 context "with user signed i
match '/things/:thing_id' => "descriptions#index", :as => :thing
resources :things, :except => [:show] do
...
resources :descriptions, :only => [:create, :index]
end
如何测试嵌套描述的:create
方法
到目前为止,我已经
context "with user signed in" do
before(:each) do
user = Factory.create(:user, :name => "Bob")
controller.stub!(:authenticate_user!).and_return(true)
controller.stub!(:current_user).and_return(user)
end
describe "PUT create" do
before(:each) do
@thing = Factory.create(:thing)
params = {"text" => "Happy Text"}
post thing_descriptions_path(@thing.id), params #Doesn't work
post :create, params #Doesn't work
end
end
end
以下方面应起作用:
describe "PUT create" do
before(:each) do
@thing = Factory(:thing)
attrs = FactoryGirl.attributes_for(:description, :thing_id => @thing)
post :create, :thing_id => @thing, :description => attrs
end
end
要创建嵌套资源,您需要在post create中告诉rspec父id,以便它可以将其插入路由
您还需要创建与内置的
:thing
关系的:description
工厂,并将thing\u id
传递到:description
属性创建中,这是为了确保Factory Girl在为:description
创建属性时不会去创建一个新的:thing
,虽然这不会导致测试失败,但它会减慢测试速度,因为您最终会创建两个:thing
的实例?是在物品说明书还是描述说明书里?应该是后者。