【发布时间】:2020-07-19 23:32:46
【问题描述】:
我有 POST 端点,它在我的数据库中创建一个新的 JourneyProgress 记录。
post :enroll do
JourneyProgress.create!(user: current_user, journey: journey, percent_progress: 0.0, started_at: DateTime.now)
status :no_content
end
我想检查percent_progress 和started_at 是否通过以下示例设置:
let(:current_date) { 'Thu, 16 Jul 2020 17:08:02 +0200'.to_date }
before do
allow(DateTime).to receive(:now) { current_date }
end
it 'set starting progress' do
call
expect(JourneyProgress.last.started_at).to eq(current_date)
expect(JourneyProgress.last.percent_progress).to eq(0.0)
end
规范会通过,但我不确定JourneyProgress.last.(some record name) 是否符合惯例。有没有更好的方法来检查这个?
如果我将其更改为:
it 'set starting progress' do
expect(call.started_at).to eq(current_date)
...
end
我收到一个错误:
NoMethodError:
undefined method `started_at' for 204:Integer
【问题讨论】:
-
您的端点返回
status :no_content(HTTP 204),这就是您在第二次使用时收到错误的原因。因此,如果您关心检查新记录的值,则需要照常查找(或简单地检查JourneyProgress记录的计数是否增加了 1)。 -
正确的状态码应该是 201 Created 并且要么包含一个带有新创建资源的位置标头,要么包含一个包含该资源的 JSON 响应正文。在这种情况下,204 响应对客户端毫无用处。
-
我会说最好检查 HTTP 响应,但这种方法也可以。
标签: ruby-on-rails ruby rspec