Rspec预计变更计数不起作用

时间:2018-01-29 13:03:11

标签: ruby-on-rails rspec capybara rspec-rails actioncable

此处我在当前用户发送有效消息后测试current_user.messages.count中的更改。这是我的代码:

规范

scenario 'adds to their messages', js: true do
  expect { find('#message_content').send_keys(:enter) }.to \
    change(current_user.messages, :count).by(1)
end

test.log中

# ...
ConversationChannel is transmitting the subscription confirmation
ConversationChannel is streaming from conversation_channel_1
   (0.6ms)  SELECT COUNT(*) FROM "messages" WHERE "messages"."user_id" = $1  [["user_id", 1]]
ConversationChannel#send_message({"content"=>"foobar\n", "conversation_id"=>"1"})
   (0.3ms)  BEGIN
   (0.9ms)  SELECT COUNT(*) FROM "messages" WHERE "messages"."user_id" = $1  [["user_id", 1]]
  Conversation Load (1.6ms)  SELECT  "conversations".* FROM "conversations" WHERE "conversations"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
   (0.7ms)  SELECT "users"."id" FROM "users" INNER JOIN "user_conversations" ON "users"."id" = "user_conversations"."user_id" WHERE "user_conversations"."conversation_id" = $1  [["conversation_id", 1]]
  SQL (1.0ms)  INSERT INTO "messages" ("content", "user_id", "conversation_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id"  [["content", "foobar\n"], ["user_id", 1], ["conversation_id", 1], ["created_at", "2018-01-29 11:27:13.095277"], ["updated_at", "2018-01-29 11:27:13.095277"]]
Finished "/cable/" [WebSocket] for 127.0.0.1 at 2018-01-29 19:27:13 +0800
ConversationChannel stopped streaming from conversation_channel_1
   (0.2ms)  BEGIN
   (58.8ms)  COMMIT
   (16.7ms)  ALTER TABLE "schema_migrations" DISABLE TRIGGER ALL;ALTER TABLE "ar_internal_metadata" DISABLE TRIGGER ALL;ALTER TABLE "conversations" DISABLE TRIGGER ALL;ALTER TABLE "messages" DISABLE TRIGGER ALL;ALTER TABLE "user_conversations" DISABLE TRIGGER ALL;ALTER TABLE "users" DISABLE TRIGGER ALL
  Rendered messages/_message.html.erb (0.6ms)
[ActionCable] Broadcasting to conversation_channel_1: {:message=>"<p>User 1: foobar\n</p>\n"}
# ...

即使在日志显示expected #count to have changed by 1, but was changed by 0实际发生时,规范也失败了INSERT INTO

2 个答案:

答案 0 :(得分:0)

尝试写: 更改{current_user.messages,:count} .by(1) 与{}

答案 1 :(得分:0)

这不起作用,因为您没有等待足够长的时间来实际发生消息添加。一旦浏览器发送了密钥事件,send_keys就会返回,但对浏览器中按键触发的任何请求/操作一无所知。这就是为什么直接数据库访问测试在功能/系统测试中通常是一个坏主意(通常应该只测试用户可见的更改/交互),并且作为请求或控制器更有意义。

话虽如此,您可以通过在发送密钥后休眠来解决此问题,但更好的解决方案是使用Capybara提供的匹配器之一(具有等待/重试行为)来同步测试。

scenario 'adds to their messages', js: true do
  expect do 
    find('#message_content').send_keys(:enter) }
     expect(page).to have_css(...) # check for whatever visible change on the page indicates the action triggered by send_keys has completed
  end.to change { current_user.reload.messages.count }.by(1)
end

注意:此测试对于功能测试也非常简单。在功能测试中有多个期望是可以的,因为它真的意味着测试整个用户与应用程序的特定功能的交互。您可能希望将此测试与应用程序相同部分的其他测试结合起来。