我有两种型号:User
和Topic
。用户可以拥有属于一个用户的许多主题和主题。为什么Test :: Unit测试不能在`post:create`中保存模型?
在我的主题控制器,我想测试一个有效的主题创建行动:
测试
# topics_controller.test.rb
def test_create_valid
sign_in Factory(:user) # Devise will redirect you to the login page otherwise.
topic = Factory.build :topic
post :create, :topic => topic
assert_redirected_to topic_path(assigns(:topic))
end
工厂(工厂女孩)
# factories.rb
Factory.define :user do |f|
f.sequence(:username) { |n| "foo#{n}"}
f.password "password"
f.password_confirmation { |u| u.password}
f.sequence(:email) { |n| "foo#{n}@example.com"}
end
Factory.define :topic do |f|
f.name "test topic"
f.association :creator, :factory => :user
end
测试输出
ERROR test_create_valid (0.59s)
ActionController::RoutingError: No route matches {:action=>"show", :controller=>"topics", :id=>#<Topic id: nil, name: nil, created_at: nil, updated_at: nil, creator_id: 1>}
/usr/local/lib/ruby/gems/1.9.1/gems/actionpack-3.0.7/lib/action_dispatch/routing/route_set.rb:425:in `raise_routing_error'
在测试中,topic.valid?
为真和topic.name
具有从工厂的值。
但是,帖子似乎并没有通过post :create, :topic => topic
。它看起来像从未保存在数据库中,因为它甚至没有在测试输出中的id。
编辑:即使我绕过工厂的新主题,它不起作用。
def test_create_valid
@user = Factory :user
sign_in @user
topic = @user.topics.build(:name => "Valid name.")
post :create, :topic => topic
assert_redirected_to topic_path(assigns(:topic))
end
结果出现相同的测试错误。
哦男人。对象vs params。我从来没有想过这件事。 – danneu 2011-05-08 03:09:08