12
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

link_toやrenderを含むActiveDecoratorを使ったメソッドのRSpecの書き方

Last updated at Posted at 2015-07-30

はじめに

ActiveDecoratorとは、Railsアプリ上で「View上に書かれているロジックを無くしたり、Viewでしか使わないロジックによるModelの肥大化を防ぐことができる」gemです。

参考 ActiveDecoratorでビューからロジックを切り離せ(要約版) - Qiita

本エントリーではActiveDecoratorで生やしたメソッドをテストする記述方法の一例を書きます。

RSpecでActionView::HelpersのメソッドがNoMethodErrorになる

app/decorators/user_decorator.rb
module UserDecorator
  def link_to_qiita_profile
    link_to "qiita_profile","http://qiita.com/#{qiita_id}"
  end
end

作成したDecoratorのメソッドをRSpecでテストすると、link_to, renderなどのActionView::Helpersメソッドがundefiend methodと怒られます。

spec/decorators/user_decorator.rb
require "rails_helper"

describe UserDecorator do
  context "extend UserDecorator" do
    let!(:user) { User.create(name: "hiromitsu ito", qiita_id: "umeyuki@github").extend(UserDecorator)}
    subject {  user.extend(UserDecorator).link_to_qiita_profile }
    it { is_expected.to eq "http://qiita.com/umeyuki@github" }
  end
end

 $ rspec spec/decorators/user_decorator.rb
F.

Failures:

  1) UserDecorator extend UserDecorator
     Failure/Error: subject {  user.extend(UserDecorator).link_to_qiita_profile }
     NoMethodError:
       undefined method `link_to' for #<User:0x007ff0cc1de380>
     # ./app/decorators/user_decorator.rb:3:in `link_to_qiita_profile'

active_decorator-rspecを使う

mizoR/active_decorator-rspec

active_decorator-rspecを使えば、この問題を解決することができます

group :test do
  gem 'rspec'
  gem 'rspec-rails'
  gem 'active_decorator-rspec'
end

サンプル

spec/decorators/user_decorator.rb
require "rails_helper"

describe UserDecorator do

  context "extend UserDecorator" do
    let!(:user) { User.create(name: "hiromitsu ito", qiita_id: "umeyuki@github").extend(UserDecorator)}
    skip "ActionView::Helpersのメソッドが使えないため失敗する" do
      subject {  user.extend(UserDecorator).link_to_qiita_profile }
      it { is_expected.to eq "http://qiita.com/umeyuki@github" }
    end
  end

  # 成功
  context "active_decorator-rspec" do
    let!(:user) { User.create(name: "hiromitsu ito", qiita_id: "umeyuki@github")}
    subject { decorate( user ).link_to_qiita_profile }
    it { is_expected.to eq "http://qiita.com/umeyuki@github" }
  end
end

デモのrailsアプリは以下です。

umeyuki/demo-active_decorator-rspec

12
8
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
12
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?