2011-05-08 93 views
0

我有两种型号:UserTopic。用户可以拥有属于一个用户的许多主题和主题。为什么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 

结果出现相同的测试错误。

回答

1

这里的post方法需要参数作为第二个参数,而不是对象。这是因为在你的控制器中的create行动将要使用params方法来检索这些参数和创建一个新课题的过程中使用它们,使用这样的代码:

Topic.new(params[:topic]) 

因此,因此您params[:topic]需求是您要创建的项目的属性,而不是现有的Topic对象。但是,你可以使用Factory.build :topic得到一个实例化Topic对象,然后这样做是为了使其工作:

post :create, :topic => topic.attributes 
+0

哦男人。对象vs params。我从来没有想过这件事。 – danneu 2011-05-08 03:09:08

0

这远远超出了我,但我显然必须手动设置post :create params中的属性。看起来很不直观,因为:topic => topic就是这样的Rails成语。

def test_create_valid 
    sign_in @user 
    topic = Factory.build :topic 
    post :create, :topic => {:name => topic.name} 
    assert_redirected_to topic_path(assigns(:topic)) 
    end 

希望有人能阐明为什么post :create, :topic => topic不起作用。

相关问题