对RSpec在视图测试中分配创建的实例变量的访问



我再次尝试请rubocop rails。在这种情况下,rails generate scaffold生成的视图规范使用实例变量(例如@import_file(

# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'import_files/edit', type: :view do
before do
@import_file = assign(:import_file, ImportFile.create!(
path: 'MyString',
file_type: 1
))
end
it 'renders the edit import_file form' do
render
assert_select 'form[action=?][method=?]', import_file_path(@import_file), 'post' do
assert_select 'input[name=?]', 'import_file[path]'
assert_select 'input[name=?]', 'import_file[file_type]'
end
end
end

RSpec样式指南不喜欢实例变量。

代码已经使用了assign,这是必需的,因为这是一个视图规范。我如何访问该变量?简单地引用它是行不通的。

有几个Stack Exchange问题提到了view_assigns,但我认为这个问题/答案值得一试。对assign创建的变量的访问是通过view_assigns[symbol]访问

require 'rails_helper'
RSpec.describe 'import_files/edit', type: :view do
subject { document_root_element }
let(:path) { import_file_path(view_assigns[:import_file]) }
let(:form_css) { "form[action='#{path}'][method=post]" }
before do
assign(:import_file, create(:import_file))
render
end
it { is_expected.to have_css(form_css) }
describe 'the rendered form' do
subject { css_select form_css }
it { is_expected.to have_field('Path', type: :file, name: 'import_file[path]') }
it { is_expected.to have_select('File type', name: 'import_file[file_type]', options: %w[qif sqlite]) }
end
end

最新更新