神戸.rb Meetup #11 に参加したよヘ(^o^)ノ
Kobe.rbに参加してきたよヘ(^o^)ノ
今日のおやつ!! photo by @spring_aki
おいしかった♪
今日、僕が調べてたのはActiveDecorator + Capybara + RSpecです。
ActiveDecoratorでhelperを良く使いますよねー
例えばこんなの...
def full_name content_tag :td do "#{first_name} #{last_name}" end end
Decoratorが自動生成するRSpecはこちら
describe UserDecorator let(:user) { User.new.extend UserDecorator } subject { user } it { should be_a User } [...] end
毎回extendするのもアレなので、ActiveDecorator::RSpecを使います
# Gemfile gem 'active_decorator-rspec' # spec/decorator/user_decorator_spec.rb describe UserDecorator # FactoryGirlでテストデータ作成 let(:user) { build(:user) } subject { decorate user } it { should be_a User } [...] end
いい感じですねー
キモのfull_nameメソッドをCapybaraでテストしてみましょう
describe UserDecorator [..] it 'has a tr tag and full_name' do expect(subject.name).to have_content(:td, "#{user.first_name} #{user.last_name}") end end
実行すると怒られます。。。
undefined method 'content_tag' for ...
type: :heler
or type: :view
を指定すればhelperメソッドが認識されますが、
こんどはCapybaraにおこられます( ̄▽ ̄;)
have_contentはCapybara::RSpecMatchersで定義されてるのでincludeしてみます
describe UserDecorator include Capybara::RSpecMatchers let(:user) { build(:user) } subject { decorate user } it { should be_a User } it 'has a tr tag' do expect(subject.name).to have_content(:td) end end
これでテストを実行すればパスしますが、毎回includeはアレなのでrails_helperに追記
# spec/rails_helper.rb RSpec.configure do |config| config.include Capybara::RSpecMatchers, type: :decorator end
describe UserDecorator let(:user) { build(:user) } subject { decorate user } it { should be_a User } it 'has a tr tag', type: :decorator do expect(subject.name).to have_content(:td, "#{user.first_name} #{user.last_name}") end end
これでCapybaraを使ってテストできますねー
Happy Hacking٩( ‘ω’ )و