LoginSignup
4
7

More than 5 years have passed since last update.

RspecでViewのテストを書く

Posted at
group :test do
  gem 'rspec-rails'
  gem 'factory_girl_rails'
  gem 'capybara'
end

@user などのインスタンス変数は assign メソッドが用意されている。
current_user などのヘルパーメソッドは自前で定義しないといけないっぽい。ここが悩んだ

spec/views/xxx/yyy.html.erb_spec.rb
RSpec.describe "xxx/yyy", type: :view do
  let(:user) { create :user }
  let(:helper_methods) {
    {
      current_user: user
    }
  }
  before { assign(:user, user) }

  it 'works' do
    define_helper_methods(view, helper_methods)
    render

    expect(rendered).to have_css('h1', text: 'Title')
  end
end
spec/support/test_helpers.rb
module TestHelpers
  def define_helper_methods(view, methods)
    methods.each do |name, value|
      view.define_singleton_method(name){ value }
    end
  end
end
spec/rails_helper.rb
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }

RSpec.configure do |config|
  config.include FactoryGirl::Syntax::Methods
  config.include Devise::Test::IntegrationHelpers, type: :request
  config.include TestHelpers
end
4
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
7