此测试点击了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/)说:
看起来这是我的问题,所以我的问题就变成了,如何在查询数据库的同时使用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