我使用的是Capybara 1.1.2,Rails 3.1.3,rspec-rails 2.9.0和
Ruby 1.9.3p0.
假设有标准和account_admin用户的应用程序.标准用户可以创建另一个标准用户,但标准用户无法创建account_admin用户.
当然,UI不会为标准用户提供创建帐户管理员的选项.但使用Firebug并且用户可以重新编写HTML 30秒,因此它会提交POST请求以创建account_admin.
我如何测试我的应用程序是否阻止了这种简单的黑客攻击?
正常的标准用户测试如下所示:
context "when standard user is signed in" do
before do
login_as standard_user
visit users_path # go to index
click_link('Add user') # click link like user would
end
describe "when fields are filled in" do
let(:new_email) { "new_user@example.com" }
before do
fill_in "Email", with: new_email
fill_in "Password", with: "password"
fill_in "Password confirmation", with: "password"
choose "Standard user" # radio button for Role
end
it "should create a user" do
expect { click_button submit }.to change(User, :count).by(1)
end
end
end
有没有办法“愚弄”测试以获取表单上不允许的值?我尝试将单选按钮视为文本字段,但Capybara拒绝将其视为不存在的字段:
fill_in "Role", with: "account_admin" # doesn't work
直接修改params散列也不起作用:
params[:role] = "account_admin" # doesn't work
我是否必须更像控制器测试,直接调用post:create?
最佳答案 Capybara作者jnicklas证实了
here,Capybara无法制作应用程序,无法从UI中获取.他建议进行授权的控制器测试.
但是,在不使用Capybara语法的情况下使用RSpec编写的请求规范允许直接使用HTML动词(以及一些其他帮助程序),如RSpec和Rails文档中所述.因此,不是Capybara的fill_in和click_link指令以及页面对象,您可以使用属性哈希,动词如get,post,post_via_redirect和response.body对象.它类似于控制器测试,但您使用Rails的路由来根据提供的路径选择适当的控制器操作.以下是后一种技术的示例:
describe "when standard user attempts to create account_admin user" do
let(:standard_user) { FactoryGirl.create(:standard_user) }
let(:attr) { { email: "account_admin@example.com",
password: "password",
password_confirmation: "password",
role: "account_admin" }
}
before do
login_as standard_user
get new_user_path
end
it "should not create a account_admin user" do
lambda do
post users_path, user: attr
end.should_not change(User, :count)
end
describe "after user posts invalid create" do
before { post_via_redirect users_path, user: attr }
# redirect to user's profile page
it { response.body.should have_selector('title', text: 'User Profile') }
it { response.body.should have_selector('div.alert.alert-error', text: 'not authorized') }
end
end