控制器找不到在测试数据库中创建的对象

时间:2014-04-25 01:11:58

标签: ruby-on-rails ruby rspec capybara factory-bot

此测试点击了show_fretboard中点击static_pages_controller.rb的链接:

describe "StaticPages" do
  subject { page }
  let!(:key) { FactoryGirl.create(:key, user: user, name: 'C') }
  .
  .
  .
  describe "the fretBoard" do
    before { visit root_path }
    it 'should appear when clicked', js: true do
      puts key.name
      puts key.id
      puts Key.find_by(name: 'C').id
      click_link 'fretBoard-side-link'
      page.should have_selector("#fretboard-key-header", :text => "Showing Notes in the Key of")
    end
  end
  .
  .
  .
end

测试的失败表明了这一点:

Run options: include {:line_numbers=>[141]}
C
9
9

An error occurred in an after hook
  NoMethodError: undefined method `id' for nil:NilClass
  occurred at /Users/user_name/rails_projects/my_project/app/controllers/static_pages_controller.rb:69:in `show_fretboard'

密钥存在,因为它输出密钥的名称和ID。当static_pages_controller.rb尝试找到密钥时,如下所示:

def show_fretboard
    @key = params[:key] || Key.find_by(name: 'C').id

抛出此错误:

undefined method `id' for nil:NilClass

为什么此查询未找到名为“C”的Key对象?

编辑:这篇文章(http://justinleitgeb.com/rails/common-rails-testing-mistakes/)说:

  • Capybara中启用Javascript的测试在另一个线程中运行
  • 您在测试示例中创建的数据库元素(来自工厂等)将不会在服务器线程中显示

看起来这是我的问题,所以我的问题就变成了,如何在查询数据库的同时使用JS测试来测试我的ajax调用。

编辑:数据库清理程序设置:

RSpec.configure do |config|
  puts 'in database_cleaner.rb'
  config.before(:suite) do
    DatabaseCleaner.clean_with(:truncation)
  end

  config.before(:each) do
    DatabaseCleaner.strategy = :transaction
  end

  config.before(:each, :js => true) do
    DatabaseCleaner.strategy = :truncation
  end

  config.before(:each) do
    DatabaseCleaner.start
  end

  config.after(:each) do
    DatabaseCleaner.clean
  end

# source: http://devblog.avdi.org/2012/08/31/configuring-database_cleaner-with-rails-rspec-capybara-and-selenium/
end

0 个答案:

没有答案