0

試圖讓這個功能測試通過:Rails的功能測試利用需要的兒童

test "should create question" do 
    assert_difference('Question.count') do 
    post :create, :question => @question.attributes 
    end 
end 

但@question有需要特定的孩子驗證是存在明確的一個課題:

class Question < ActiveRecord::Base 
    has_many :topic_questions 
    has_many :topics, :through => :topic_questions 

    validate :has_topic 

    def has_topic 
     (errors[:base] << "You must have one topic") if (topics.count < 1) 
    end 
    end 

會如何我1)在測試中爲@question構建主題,然後2)將它傳遞給post方法,因爲它不會被.attributes()函數傳遞?

回答

1
 
test "should create question" do 
    assert_difference('Question.count') do 
    @question.topics<<Topic.new(**set topics required and attribute here) 
#or try this line of code 
    @question[:topics]={:name=>"bla bla" ** set attribute here what u need} 
    post :create, :question => @question.attributes 
    end 
end 
+0

有沒有辦法使用以下方法做同樣的事情? `後:創建,問題:{主題:@a_topics_array}` – 2013-01-07 20:21:41

0

測試沒問題,它是需要更改的控制器和/或模型。你沒有表現出create行動的內容,但基本上有兩種方法可以做到這一點:

@question = Question.new(params[:question]) 
@question.build_topic(<some_params>) 
if @question.save 
    # ... etc ... 

或者,在Question模型中使用accepts_nested_attributes_for :topic,然後通過在params哈希表的主題參數。哪種方法最好取決於您的具體情況。