ruby-on-rails - 在 capybara 测试中, Controller 改变了一个对象,期望不会拾取它

标签 ruby-on-rails ruby capybara-webkit

我正在使用 capybara 和 webkit 驱动程序进行集成测试,我想测试用户是否可以停用他的帐户来覆盖设计 Controller ,覆盖工作正如我看到的绑定(bind) pry 一样,它确实改变了用户。

这是用户模型上的相关代码

class User < ActiveRecord::Base
  [...]
  def deactivate!
    self.deactivated = true
    self.deactivated_at = Time.zone.now
    self.save!
    # binding.pry here shows that the user with id 1 changed
  end
end

我重写了 devise destroy 方法,这是一个只更改了一行的复制粘贴

class RegistrationsController < Devise::RegistrationsController
  def destroy
    resource.deactivate!
    # binding.pry shows that the user was actually deactivated
    Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name)
    set_flash_message :notice, :destroyed if is_navigational_format?
    respond_with_navigational(resource){ redirect_to after_sign_out_path_for(resource_name) }
  end
end

现在是问题的核心,测试

feature 'registration' do
  let(:user) { create(:user) }

  scenario 'user can deactivate his account' do
    # binding.pry show that the user was created with id 1
    # And now i perform steps to login the user
    visit root_url
    click_link 'Sign in'
    fill_in 'Email', with: user.email
    fill_in 'Password', with: user.password
    click_button 'Log in'
    # binding.pry shows that the user last_login_at was actually correctly updated, so the login works

    # We need rack tests driver because the webkit driver does not support custom HTTP methods
    current_driver = Capybara.current_driver
    Capybara.current_driver = :rack_test
    # Actual submit
    page.driver.submit :delete, user_registration_path, {} # this triggers the deactivate method

    Capybara.current_driver = current_driver

    # binding.pry shows that user was not touched at all!
    expect(user).to be_deactivated # so this fails :(
  end
end

也许我遗漏了有关机架测试驱动程序的一些信息,它回滚了更改,查看 tail -f log/test.log 我没有看到回滚,但我确实看到了 释放保存点 active_record_1 在停用方法之后,有什么想法吗?

最佳答案

问题在于规范中加载的用户对象是在基础数据更改之前加载的。您需要重新加载用户对象才能看到所做的更改:

expect(user.reload).to be_deactivated

关于ruby-on-rails - 在 capybara 测试中, Controller 改变了一个对象,期望不会拾取它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26028675/

相关文章:

Ruby on Rails regexp equals-tilde 与 array include 用于检查选项列表

ruby - 无法在 Ubuntu 14.04 上安装 Ruby Capybara-webkit 1.4.1

ruby-on-rails-3 - Capybara::FrozenInTime 使用 Rspec + Timecop + Capybara + Capybara Webkit 的集成规范中的错误

ruby-on-rails - 在公共(public)属性上连接两个 ActiveRecord 关联

ruby-on-rails - 您如何为下一个项目选择合适的 Ruby gem?

ruby-on-rails - 如何重定向到特定 Controller ?

ruby-on-rails-3 - Rails3 form_for hidden_​​field 未定义方法 'merge'

ruby-on-rails - Rails 5 ActiveRecord 查询

ruby - 为什么 ruby​​ 父类假定其子类的类变量?

ruby 做映射和压缩在一起