如何干掉这个RSpec控制器规格?

时间:2016-08-23 19:12:40

标签: ruby-on-rails ruby rspec

如何干这个规格?

describe Api::TasksController, type: :controller do
  it 'allows the creator of a task to destroy it' do
    set_request_auth_header @user
    delete :destroy, id: @task.id
    expect(response).to be_success
    expect(Task.count).to eq 0
  end

  it 'does not allow the assignee of a task to destroy it' do
    set_request_auth_header @assignee
    delete :destroy, id: @task.id
    expect(response).to be_forbidden
    expect(Task.count).to eq 1
  end

  it 'does not allow anyone unrelated to a task to destroy it' do
    set_request_auth_header @spy
    delete :destroy, id: @task.id
    expect(response).to be_forbidden
    expect(Task.count).to eq 1
  end
end

2 个答案:

答案 0 :(得分:0)

你不这样做。瞧,欢迎你。

答案 1 :(得分:0)

您可以提取一些方法:

describe Api::TasksController, type: :controller do
  it 'allows the creator of a task to destroy it' do
    expect_delete_to_succeed @user
  end

  it 'does not allow the assignee of a task to destroy it' do
    expect_delete_to_be_forbidden @assignee
  end

  it 'does not allow anyone unrelated to a task to destroy it' do
    expect_delete_to_be_forbidden @spy
  end

  def expect_delete_to_succeed(requester)
    delete_task requester
    expect(response).to be_success
    expect(Task.count).to eq 0
  end

  def expect_delete_to_be_forbidden(requester)
    delete_task requester
    expect(response).to be_forbidden
    expect(Task.count).to eq 1
  end

  def delete_task(requester)
    set_request_auth_header requester
    delete :destroy, id: @task.id
  end

end

附注:

  • 使用实例(@)变量不是RSpec中的当前标准做法。查看let 'variables'
  • Task.exists? @task.id似乎比检查Task.count更清楚地检查删除。