我设置的路线如下:
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
答案 0 :(得分:3)
以下内容应该有效:
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
要创建嵌套资源,您需要告诉rspec post创建的父ID,以便它可以将其插入到路径中。
您还需要创建与:descriptions
内置关系的:thing
工厂,并将thing_id
传递给:description
属性创建,这是为了制作确保Factory Girl在创建:thing
的属性时不会创建新的:description
,虽然这不会导致测试失败,但会降低速度,因为您最终会创建:thing
的两个实例。