1
我是新來測試,並知道有類似的問題,但我無法找到一個很好的答案在任何地方,所以我想我得到了一勞永逸。測試嵌套資源CRUD與Rspec和FactoryGirl一勞永逸
我有項目資源有許多任務。 I 希望使用Factory Girl正確測試tasks_controller_spec.rb中的任務CRUD操作。怎麼做?
這是我的代碼到目前爲止,讓你開始...
的routes.rb
5 resources :projects do
6 resources :tasks
7 end
factories.rb
1 FactoryGirl.define do
2
3 factory :valid_project, :class => Project do
4
5 sequence(:name) do |n|
6 "FactoryProject - #{n}"
7 end
8 sequence(:description) do |n|
9 "Description for the FactoryProject - #{n}"
10 end
11
12 end
13
14 factory :valid_task, :class => Task do
15
16 sequence(:name) do |n|
17 "FactoryTask - #{n}"
18 end
19 sequence(:description) do |n|
20 "Description for the FactoryTask - #{n}"
21 end
22 valid_project
23
24 end
25
26 end
tasks_controller_spec.rb
1 require 'spec_helper'
2
3 describe TasksController do
4
5 before :each do
6 @valid_project = FactoryGirl.create :valid_project
7 end
8
9 describe 'Success' do
10
11 before :each do
12 @valid_attr = FactoryGirl.attributes_for :valid_task
13 end
14
15 it 'Should create new task' do
16 lambda do
17 post :create, :project_id => @valid_project, :task => @valid_attr
18 end.should change(Task, :count).by(1)
19 end
20
21 #it 'Should update the task' do
22 #end
23
24 end
25
26 describe 'Failure' do
27
28 before :each do
29 @invalid_attr = { :name => '', :description => '' }
30 end
31
32 it 'Should not create new task' do
33 lambda do
34 post :create, :project_id => @valid_project, :task => @invalid_attr
35 end.should_not change(Task, :count)
36 end
37
38 end
39
40 end
謝謝!使用attributes_for與構建相反有什麼區別嗎?另外,如果您知道'tasks_controller_spec.rb'的代碼,以測試基本的CRUD功能,我將非常感謝... – oFca 2012-05-01 21:19:37
build在內存中創建一個對象,但不會將其保存到數據庫。你仍然可以通過@ task.attributes獲得它的屬性。如果你想要的屬性,attributes_for可能會更好,我只是不知道你如何填充關聯。 – 2012-05-01 21:56:01