Rails Rspec 3 View Test Examples
- Last modified atI use Rspec View for testing required html tags, required partial, or conditional in html. Here are some examples View specs with Rspec 3.7.
Conditional and Required HTML Tags Assertions
# spec/views/posts/index.html.slim_spec.rb
Rspec.describe 'posts/index', type: :view do
let(:user) { User.first }
before do
@posts = assign(:posts, Post.limit(2))
end
context 'when user is signed in' do
before do
# mock current_user
allow(view).to receive(:current_user).and_return(user)
end
it 'shows edit link' do
render
expect(rendered).to have_css('#name', text: user.name)
assert_select 'table' do
assert 'tr:nth-child(1)' do
assert_select 'td:nth-child(1)', "#{@posts.first.title}"
assert_select "#edit-post-#{@posts.first.id}", 'Edit'
end
assert 'tr:nth-child(2)' do
assert_select 'td:nth-child(1)', "#{@posts.second.title}"
assert_select "#edit-post-#{@posts.second.id}", 'Edit'
end
end
end
end
context 'when user is not signed in' do
it 'does not show edit link' do
render
expect(rendered).not_to have_css('#name', text: user.name)
assert_select 'table' do
assert 'tr:nth-child(1)' do
assert_select 'td:nth-child(1)', "#{@posts.first.title}"
assert_select "#edit-post-#{@posts.first.id}", false
end
assert 'tr:nth-child(2)' do
assert_select 'td:nth-child(1)', "#{@posts.second.title}"
assert_select "#edit-post-#{@posts.second.id}", false
end
end
end
end
end
Partial and content_for Assertions
# spec/views/posts/show.html.slim_spec.rb
Rspec.describe 'posts/show', type: :view do
it 'renders sidebar partial and content_for content' do
render
expect(view.content_for(:title)).to eq t(:page_title_translation)
expect(rendered).to render_template(partial: 'shared/_sidebar')
end
end
Sponsored Links
- Register to Digital Ocean cloud with this link and get $200 credit
- Looking for cheap CDN? Bunny is the answer
- Alternative Cloud besides AWS and Digital Ocean