对 AASM 抛出的错误进行故障测试 gem

Trouble testing for an error thrown from AASM gem

我在测试抛出的 AASM 错误时遇到问题。

这是我的控制器方法:

# controllers/jobs_controller.rb
def change_state
  respond_to do |format|
    if @job.close && @job.save
      format.html { redirect_to @job, notice: 'Job has been closed.' }
      format.json { render :show, status: :ok, location: @job }
    else
      format.html { render :show, notice: 'Job could not be closed.' }
      format.json { render json: @job.errors, status: :unprocessable_entity }
    end
  end
end

我的规格是这样的:

# spec/controllers/jobs_controller_spec.rb
describe "POST #change_state" do
  it "cannot transition job from closed" do
    job.aasm_state = "closed"
    job.save!
    post :change_state, params: {id: job.hash_id, user_id: user.id}
    expect { response }.to raise_error(AASM::InvalidTransition)
  end
end

测试失败(expected/desired 失败):

Failure/Error: if @job.close && @job.save     
AASM::InvalidTransition:Event 'close' cannot transition from 'closed'.

我只是想不出正确的语法来通过测试。我尝试了 expect 行的几种变体,但似乎无法将它们拼凑在一起。

感谢任何指导。

异常发生在 expect 语句之前。试一试:

expect {
  post(:change_state, params: { id: job.hash_id, user_id: user.id })
}.to(
  raise_error(AASM::InvalidTransition)
)