Capybara的click_link和Rails控制器动作 - 测试是否应该通过?

时间:2014-04-25 06:01:34

标签: ruby-on-rails capybara

我正在开发时为我的引擎编写Capybara集成测试。

我有一个集成测试来检查帐户所有者是否可以实际删除用户。它使用' destroy'用户控制器的动作。

根据我的理解,Capybara的默认驱动程序将在您未使用启用了javascript的驱动程序时单击链接时执行GET,以便“销毁”#39;'实际上不应该调用动作,测试应该失败。事实上,我还没有包括默认的rails javascripts。

然而,当我打开Chrome浏览器窗口并手动执行序列时,按下删除链接的Capybara测试实际上通过了测试,即使它按预期失败。

用户代码:

查看:show.html.slim

h2 User

= @user.to_yaml

= link_to 'Edit User',  edit_user_path(@user) if policy(@user).edit?
br
= link_to 'Delete User',  user_path(@user), method: :delete if policy(@user).destroy?

控制器:users_controller.rb

module Subscribe
  class Account::UsersController < Account::BaseController
    def index
      @users  = current_account.users
    end

    def show
      @user = current_account.users.find_by(id: params[:id])
      authorize @user
    end

    def new
      @user = User.new
      @user.account_id = current_account.id # required for authorize
      authorize @user
    end

    def edit
      @user = current_account.users.find_by(id: params[:id])
      authorize @user
    end

    def update
      @user = current_account.users.find_by(id: params[:id])
      authorize @user

      do_new_sign_in = (current_user == @user)

      if @user.update_attributes(user_params)
        sign_in(@user, bypass: true) if  do_new_sign_in

        flash[:success] = "Update successful."
        redirect_to @user
      else
        render 'edit'
      end
    end

    def create
      @user = User.new(user_params)
      @user.account_id = current_account.id
      authorize @user

      if @user.save
        flash[:success] = "User successfully added."
        redirect_to users_path
      else
        flash.now["Sorry, could not create a new user. Please review the error messages."]
        render :new
      end
    end

    def destroy
      @user = current_account.users.find_by(id: params[:id])
      authorize @user

      @user.destroy
      flash[:success] = "User successfully deleted."
      redirect_to users_path

    end

    private

    def user_params
      params.require(:user).permit(
        :email,
        :password,
        :password_confirmation
      )
    end
  end
end

测试:spec / features / users / sign_up_authorization.rb

scenario "Can delete user" do
    click_link "#{user1.email}"

    click_link "Delete User"

    success_message = "User successfully eleted."
    expect(page).to have_content(success_message)
end

1 个答案:

答案 0 :(得分:0)

由于这些链接非常常见,因此机架测试驱动程序具有代码(see source)来检测此情况,并使用正确的方法跟踪链接。