Ruby-on-rails – How to test posts in Rails / Capybara / Cucumber or Rspec

capybaracucumberrspecruby-on-rails

I'm using rspec, cucumber and capybara and I'm looking for a way to test that a malicious user can't hack a form then post to an url he/she doesn't have permission to. I have my permissions set up in cancan such that this "should" work, however, the only way I can test it is by hacking a form myself.

How can I automate this sort of testing? With webrat I could do this in a unit test with rspec with something like

put :update, :user_id => @user.id, :id => @user_achievement.id
response.should contain("Error, you don't have permission to access that!") 

In capybara, however, visit only does get's it seems. I can't find a way to do this, I've googled everwhere.

Any help would be much appreciated,
Thanks

Best Answer

I think you can do this with rack-test https://github.com/brynary/rack-test

in your Gemfile:

gem 'rack-test'

in your env.rb file

module CapybaraApp
  def app; Capybara.app; end
end
World(CapybaraApp)
World(Rack::Test::Methods)

step defintions somewhere:

When /^I send a POST request to "([^"]*)"$/ do |path|
  post path
end

Most of what I learned came from here: http://www.anthonyeden.com/2010/11/testing-rest-apis-with-cucumber-and-rack-test

UPDATE: I think you can skip the changes to your env.rb file with newer versions of Rails and/or Cucumber (not sure which, I just don't do that part on my newer projects and it works fine)

Related Topic