RSpec test destroy method (Rails Tutorial 3.2 Ch. 9, Ex. 10)

元气小坏坏 提交于 2019-12-02 18:21:06

You are confusing rspec-rails request specs which are integration tests and are executed in a simulated browser and controller specs which test controller in isolation. delete(action, *args) (and get, post and so on) - is a method simulating request from ActionController::TestCase, so it's not available in your test.

So your only option is to simulate a click in a browser. I don't know how you hide your delete link, if the html is there but hidden you should be able to click it. If it's not there (removed on the server side when generating view) you can use capybara's page.execute_script (but you have to enable javascript for this example :js => true). You can either add the link back:

page.execute_script("$('body').append("<a href="/users/1" data-method="delete" rel="nofollow">Destroy</a>")")

or make ajax call:

page.execute_script("$.ajax({type:'DELETE',url:'/users/1'})")

Didn't test but something like this should work.

I solved this same problem using the following:

describe "should not be able to delete themselves" do
  it { expect { delete user_path(admin) }.not_to change(User, :count) }
end

CallumD's solution worked for me, and seemed the most consistent with the techniques recommended in the rest of Michael Hartl's tutorial. But I wanted to tighten up the syntax a little to make it more consistent with the other specs in the same tutorial:

it "should not be able to delete itself" do
  expect { delete user_path(admin) }.not_to change(User, :count)
end

This is what I ended up with (Rspec 3.2):

describe 'DELETE destroy' do
  before :each do
    delete :destroy, { id: current_partner_role }
  end

  it 'destroys role' do
    expect(assigns(:role).destroyed?).to be true
  end

"destroyed?" method itself is spec-ed by Rails so IMHO it should be ok to rely on it.

https://github.com/rails/rails/blob/5142d5411481c893f817c1431b0869be3745060f/activerecord/lib/active_record/persistence.rb#L91

DVG

Try this:

expect { delete :destroy, :id => admin }.to_not change(User, :count)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!