如何在Rails中测试更新方法

Atl*_*tle 23 ruby-on-rails functional-testing

我正在努力测试Rails中的更新方法.我正在使用标准的内置测试框架(test::unit)和Rails 3.0.8.我已经创建了一个最小的应用程序来测试它,但我无法让它工作.这是我做的:

我创建了一个新的空白rails应用程序:

rails new testapp
Run Code Online (Sandbox Code Playgroud)

创建一个名为Collection的模型:

rails generate model collection name:string
Run Code Online (Sandbox Code Playgroud)

运行rake db:migrate:

rake db:migrate
Run Code Online (Sandbox Code Playgroud)

使用更新方法创建名为Collections的控制器:

rails generate controller collections update
Run Code Online (Sandbox Code Playgroud)

在collection_controller.rb中,我添加了这个最小更新方法:

def update
  @collection = Collection.find(params[:id])
  @collection.update_attributes(params[:collection])
end
Run Code Online (Sandbox Code Playgroud)

测试夹具是默认值(collections.yml):

one:
  name: MyString

two:
  name: MyString
Run Code Online (Sandbox Code Playgroud)

然后我将它添加到功能下的collection_controller_test.rb中:

test "should update collection" do
  put :update, :id => collections(:one), :collection => {:name => 'MyString2'}
  assert_equal "MyString2", collections(:one).name
end
Run Code Online (Sandbox Code Playgroud)

当我运行测试时:

rake test:functionals
Run Code Online (Sandbox Code Playgroud)

它失败了这条消息:

test_should_update_collection(CollectionsControllerTest) [/Users/atle/Documents/Rails/testapp/test/functional/collections_controller_test.rb:6]:
<"MyString2"> expected but was
<"MyString">.
Run Code Online (Sandbox Code Playgroud)

以下是test.log的输出:

[1m[36mSQL (0.2ms)[0m  [1m SELECT name
FROM sqlite_master
WHERE type = 'table' AND NOT name = 'sqlite_sequence'
[0m
[1m[35mCollection Load (0.1ms)[0m  SELECT "collections".* FROM "collections" WHERE "collections"."id" = 980190962 LIMIT 1
Processing by CollectionsController#update as HTML
Parameters: {"id"=>#<Collection id: 980190962, name: "MyString", created_at: "2011-06-12 13:14:13", updated_at: "2011-06-12 13:14:13">, "collection"=>{"name"=>"MyString2"}}
[1m[36mCollection Load (0.2ms)[0m  [1mSELECT "collections".* FROM "collections" WHERE "collections"."id" = 980190962 LIMIT 1[0m
[1m[35mAREL (0.2ms)[0m  UPDATE "collections" SET "name" = 'MyString2', "updated_at" = '2011-06-12 13:14:13.394135' WHERE "collections"."id" = 980190962
Rendered collections/update.html.erb within layouts/application (1.5ms)
Completed 200 OK in 9ms (Views: 4.5ms | ActiveRecord: 1.2ms)
Run Code Online (Sandbox Code Playgroud)

在日志中我可以看到UPDATE声明,但我从未看到过新的SELECT声明.

有人可以向我解释一下我做错了吗?

Ted*_*ddy 17

您可以对HTTP响应期间创建的实例变量进行断言:

test "should update collection" do
  put :update, :id => collections(:one), :collection => {:name => 'MyString2'}
  assert_equal "MyString2", assigns(:collection).name
end
Run Code Online (Sandbox Code Playgroud)


Cam*_*lsh 15

您正在重新加载夹具数据而不是从数据库中读取数据.尝试类似的东西

assert_equal "MyString2", Collection.find(collections(:one)).name
Run Code Online (Sandbox Code Playgroud)

您可能需要在夹具中指定id.

免责声明:我没有测试过这个.