我有两个模型:User
和Topic
. 用户可以有多个主题,主题属于一个用户。
在我的主题控制器中,我正在尝试测试有效主题的创建操作:
考试
# 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
导致相同的测试错误。