LoginSignup
8
8

More than 5 years have passed since last update.

viewのspecを書く

Last updated at Posted at 2013-04-06

Capybaraのセレクタで要素を検証する

CapybaraはWebブラウザをシミュレートしてCucumberでのWebアプリケーションの受け入れテストの記述をサポートするものだけど、Viewのspecを書くのにも使える。

group :test do
  gem 'capybara'
end

これでbundle installすれば spec の中で `have_selector'が使えるようになる。
have_selecorの第1引数は css selector を渡すようになっている。

hoge.html.erb_spec.rb
describe 'users/sessions/new.erb.html' do
  subject { render }

  it 'ログインフォームを表示する' do
    subject.should have_selector('input[type=email][name="user[email]"]')
    subject.should have_selector('input[type=password][name="user[password]"]')
  end
end

css selector のほか、XPathで要素を指定するメソッドも用意されている。

参考: File: README — Documentation for jnicklas/capybara (master)

helperをstubする

fuga.html.erb_spec.rb
describe 'users/sessions/new.erb.html' do
  subject { render }

  context 'notice メッセージが設定されている場合' do
    before do
      view.stub(:notice) { "hoge" }
    end

    it "noticeメッセージが出力される" do
      subject.should have_content("hoge")
    end
  end
end

参考: view spec - RSpec Rails - RSpec - Relish

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