gpt4 book ai didi

ruby-on-rails - 如何在 Rails 中测试更新方法

转载 作者:行者123 更新时间:2023-12-01 14:03:09 24 4
gpt4 key购买 nike

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

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

rails new testapp

创建一个名为 Collection 的模型:
rails generate model collection name:string

运行 rake db:migrate:
rake db:migrate

使用更新方法创建一个名为 Collections 的 Controller :
rails generate controller collections update

在 collection_controller.rb 中,我添加了这个最小更新方法:
def update
@collection = Collection.find(params[:id])
@collection.update_attributes(params[:collection])
end

测试装置是默认值 (collections.yml):
one:
name: MyString

two:
name: MyString

然后我将它添加到 collection_controller_test.rb 下的功能:
test "should update collection" do
put :update, :id => collections(:one), :collection => {:name => 'MyString2'}
assert_equal "MyString2", collections(:one).name
end

当我运行测试时:
rake test:functionals

它失败并显示以下消息:
test_should_update_collection(CollectionsControllerTest) [/Users/atle/Documents/Rails/testapp/test/functional/collections_controller_test.rb:6]:
<"MyString2"> expected but was
<"MyString">.

以下是 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)

在日志中我可以看到 UPDATE声明,但我从来没有看到新的 SELECT陈述。

有人可以向我解释我做错了什么吗?

最佳答案

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

assert_equal "MyString2", Collection.find(collections(:one)).name

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

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

关于ruby-on-rails - 如何在 Rails 中测试更新方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6322183/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com