2011-05-08 90 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不起作用。

相關問題