rspec,capybara,poltergeist,summernote , How to set text into Summernote textarea with Capybara + Poltergeist

How to set text into Summernote textarea with Capybara + Poltergeist


Tag: rspec,capybara,poltergeist,summernote

I have a textarea which is using Summernote and I set onChange event to it. I want to write test with RSpec + Capybara + Poltergeist to confirm the onChange event is working.

As far as I checked, the textarea displayed in browser is actually div tag with 'note-editable' css class. How can I set text to it and fire onChange event?

I wrote a code like this, but got an error Capybara::ElementNotFound: Unable to find field "Some label":

visit edit_foo_path
fill_in 'Some label', with: 'Foo bar'


I created a sample app for this issue:


<!DOCTYPE html>
  <link rel="stylesheet" media="all" href="/assets/application.self-f866ffa01bf26be2b8a8ac982e49d917be3b9a46604dfdc9fc8c139b62409465.css?body=1" data-turbolinks-track="true" />
  <script src="/assets/jquery.self-d03a5518f45df77341bdbe6201ba3bfa547ebba8ed64f0ea56bfa5f96ea7c074.js?body=1" data-turbolinks-track="true"></script>
<script src="/assets/jquery_ujs.self-ca5248a2fad13d6bd58ea121318d642f195f0b2dd818b30615f785ff365e8d1f.js?body=1" data-turbolinks-track="true"></script>
<script src="/assets/bootstrap.self-2bbd2c0465f01b1f8270958ddfc2e62a08915f295a35d22df2971eb936cf3c64.js?body=1" data-turbolinks-track="true"></script>
<script src="/assets/summernote.self-612431947ae9c3f1f0283dbbbc757153947f8e5de408f9bd8886b1232e8a54f7.js?body=1" data-turbolinks-track="true"></script>
<script src="/assets/blogs.self-b9a3bc0ee16e0bc44fb466bd5c7833ebec276447634d25729280397c65cff176.js?body=1" data-turbolinks-track="true"></script>
<script src="/assets/application.self-f8806224e027f3e3f0138ea9ce99319e298dfdb323304d1f1be6eae8e8c74724.js?body=1" data-turbolinks-track="true"></script>
  <meta name="csrf-param" content="authenticity_token" />
<meta name="csrf-token" content="4iu31ugTgvMERb1xQRjtcySSssjMthLWclgiHMe60aHGMeC3IMeNKZlkfFSKT33hNuvDqUUgUNTUaQEcoBl9mw==" />

<h1>New Blog</h1>

<form class="new_blog" id="new_blog" action="/blogs" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="&#x2713;" /><input type="hidden" name="authenticity_token" value="TBkcVk38/42Cx9coe717KKpb1H2cmDpv8kz7LREfkiloA0s3hSjwVx/mFg2w6uu6uCKlHBUOeG1Ufdgtdrw+Ew==" />

  <div class="field">
    <label for="blog_title">Title</label><br>
    <input type="text" name="blog[title]" id="blog_title" />
  <div class="field">
    <label for="blog_content">Content</label><br>
    <textarea class="summernote" name="blog[content]" id="blog_content">
  <div class="actions">
    <input type="submit" name="commit" value="Create Blog" />

<a href="/blogs">Back</a>



$ ->


require 'rails_helper'

feature 'Blogs' do
  scenario 'Create blog' do
    visit new_blog_path
    fill_in 'Title', with: 'Hello, world!'
    fill_in 'Content', with: 'This is awesome blog.'
    click_button 'Create Blog'
    expect(page).to have_content 'Blog was successfully created.'
    expect(page).to have_content 'Hello, world!'
    expect(page).to have_content 'This is awesome blog.'

  scenario 'Create blog with JS', js: true do
    visit new_blog_path
    fill_in 'Title', with: 'Hello, world!'
    pending 'Capybara::ElementNotFound: Unable to find field "Content"'
    fill_in 'Content', with: 'This is awesome blog.'
    click_button 'Create Blog'
    expect(page).to have_content 'Blog was successfully created.'
    expect(page).to have_content 'Hello, world!'
    expect(page).to have_content 'This is awesome blog.'


Capybaras fill_in only works with html form elements. Since the JS version of your page is using a DIV with the contenteditable attribute as its text area to be filled #fill_in will not work. Instead you need to find the div and call #set on it directly. In your project the following should work

find('div[contenteditable]').set('This is awesome blog.')


RSpec test for rake task

I have created a custom rake task that deletes all items that are >= 7 days old. I am trying to write a RSpec test for this new task but it seems like my task isn't really running in the test. I have tested the task manually and it works...

Faking instance variable in RSpec and Capybara feature spec

I'm trying to set up some feature specs before I get into refactoring some of my company's old code. It's kind of an unconventional setup, but I was able to figure out enough about test doubles to bypass the authentication enough to get started. One problem I'm still having is...

Not able to run rspec with Sequel

I am using "rspec_sequel_matchers" gem and followed the steps mentioned in the documentation. But when i run the rspec it says " uninitialized constant RspecSequel (NameError)". Help much appreciated.

How to delete an entire array in Ruby and test with RSpec

I'm fairly new to Ruby and am currently taking a full stack course. For one of my projects we are building an addressbook. I have set up how to add an entry to the addressbook, however, I can't seem to figure out how to delete an entry (I make an...

Rails / RSpec factory girl testing with invalid model produces strange behaviour

I am testing my rails controller with rspec and factory_girl My actions returns error messages in json format with 412 status in case of invalid attributes format.json{render json: user.errors.messages, status: 412} like this When I am trying to test the functionality let(:invalid_attributes){ FactoryGirl.attributes_for(:user,password: "password") } it "returns error if invalid...

Route Not Working in Rspec

Given the follow rails route ... post '/a/link.aspx', to: 'vendor_simulator#an_action' and the route shows as ... Prefix Verb URI Pattern Controller#Action POST /a/link.aspx(.:format) vendor_simulator#an_action And the following passing test ... it "returns http success" do post :an_action, return_xml, :content_type => 'application/xml' expect(response).to have_http_status(:success) end Why does the following test fail...

Rails Request Rspec Jbuilder, request.body is a StringIO object

I'm working on a project in Ruby on Rails, and I decided to use Jbuilder for handling the json serialization of my models. However when using Rspec to test my controllers with request specs, using the *.json.jbuilder views, my request.body comes back as a StringIO object, not a String. My...

RSpec controller test error: controller does not implement method

I've written some custom code for Devise registration. Namely once a user hits the "sign up" button, Devise's generic code ensures that the user is saved correctly. But then, I want to go in and make sure that the user gets an associated Stripe customer account. Most of the code...

Rspec: Factory Girl & Complex Associations

I am trying to test a helper method that would return the amount of Subscribers a Campaign is targeting. Being fairly new to TDD, I am having a hard time wrapping my head around how to write this one since the associations are quite complex. A Campaign "targets" by whether...

how to add template file in rspec-puppet

I have below manifests for sudo user, loading template file class sudo { if $::operatingsystemmajrelease < 7 { $variable = $::operatingsystemmajrelease ? { '6' => $::fqdn, } file { '/etc/sudoers' : ensure => present, owner => 'root', group => 'root', mode => '0440', content => template('sudo/sudoers.erb'), } } } Below...

How to test Devise user was created with proper password with RSpec

Is there a way to test that a Devise user was created with the correct password in RSpec? I have a feature spec for creating a user, and have tried testing that created_user.encrypted_password eq same_as_created_user).encrypted_password but the passwords generated do not match....

Capybara::ElementNotFound radio by id

I understand the syntax for Capybara choosing a radio button is the following choose("Label Name") I am running into an issue with doing this for a label that has its default name changed to an #id. Here is my HTML <label for="school_application_I_20"> Do you require an I-20 Form?</label> <br> <label...

Rspec can't stub where or find_by_, only find

I'm going to share several pairs of run code and test code. Basically, the test code is only working when I use a find on the object class, but the problem is find is the one method I DON'T want to use because I'm not looking for the primary key!...

Using Rspec should_receive to test that a controller calls a method on an object correctly

OK first, I should say while I've read a lot about should_receive, I'm still not entirely sure I'm understanding the concept behind it, so what I'm doing could potentially be completely not possible. I have the following: class PlansController def destroy plan = plan.find_by_id(params[:id]) if plan.cancel_stripe_subscription(params[:reason]) flash[:success] = "success" redirect_to...

Rspec view test with url parameters

I have a page dashboard.html.erb that may be redirected to from several different controllers/actions. When it receives the redirect, it also receives several url parameters. Controller code: class PlansController def some_action redirect_to dashboard_path(show: "default", cool_array: ["test", "test"]) end end class StaticpagesController def dashboard end end View code: <% if cool_array...

How to remove entries using a model function?

I am working on a rails assignment that wants a remove_entry method within the model and a working test for remove_entry. I am having some trouble making the test pass. Does anyone have any recommendations on how to define the remove_entry method within addressbook.rb and also how to write the...

Trouble in RSpec test - saving parent record twice

I'm new at Rails programming, and my RSpec test is failing when trying to save nested records. The logs from the test suggest that ActiveRecord is trying to save the parent twice, which results in a silent database save failure. sign_up_spec.rb (sorry for the omission!) require 'rails_helper' RSpec.feature "Accounts", type:...

Rspec, can you stub a method that doesn't exist on an object (or mock an object that can take any method)?

This might sound like a terribly basic question... so let me explain the context. I'm retrieving an event from Stripe, but for the purposes of this, but this works for other things that I've considered. The data that I need in the Stripe object is way buried, so I'd have...

How to diagnose slow rails / rake / rspec tasks

I always have a significant delay (c.10 seconds) when running tasks like: rails server rake assets:precompile rspec spec The delay is at the point before it says: Connecting to database specified by database.yml I've found several articles identifying 10 or more different parameters that can be tuned to speed up...

How to set text into Summernote textarea with Capybara + Poltergeist

I have a textarea which is using Summernote and I set onChange event to it. I want to write test with RSpec + Capybara + Poltergeist to confirm the onChange event is working. As far as I checked, the textarea displayed in browser is actually div tag with 'note-editable' css...

Rails / Rspec: How would I test #any? for Sidekiq?

I have a block: def already_syncing? { |q| q.args[0] == car_id } end How would I test this? If I stub it out like this: allow(Sidekiq::Queue).to receive_message_chain(:new, :any?) { true } Then the condition in my actual block is not tested....

model's class trying to access database even using double

I have a model structure like this models/ -- a.rb -- b.rb -- project_a/ ---- a.rb ---- b.rb the classes inside the folder project_a are classes from another Rails project. I don't have the migrations for them, I just use them to call find. It is a project to migrate...

Replace fixtures with factory girl in for generated scffold test cases

I have generated a scaffold which auto generated specs for me,If I want to replace the default fixtures with factories of factory girl what is the procedure If I replace the Model.create! with Test cases fails for GET #index assigns all tag_menus as @tag_menus DELETE #destroy destroys the requested...

Rspec routing test not passing

The below rspec test is not passing, I'm not sure what I'm doing wrong. It routes fine in the browser, but the test is not passing. require 'spec_helper' describe QueueVideosController do describe "GET show" do context "with authenticated users" do it "routes /queue to the QueueVideos controller" do expect(get("/queue")).to route_to("queue_videos#show")...

Using validate_presence_of with strict validations

I’m using the Shoulda gem. I’m using the validate_presence_of method. It is working nicely. It doesn’t seem to work, however, when using a strict validation. Example: class Thing < ActiveRecord::Base validates :status, presence: true # works validates :status, presence: true, strict: true # does not work end describe Thing do...

Run block once before all capybara tests

I'm using Capybara with Rspec for integration testing a rails app. Is there any way to run a before block once before the first Capybara test runs without it running before every feature spec? Putting a block in my RSpec.configure block as such causes it to run before each feature...

Specific test behaviour for ruby gem — mocking sleep

So I made a ruby gem that makes use of the sleep function. Using the gem in my applications causes the sleep function to be called in my tests. What is the preferred approach to dealing with this? Right now, I'm mocking out sleep in the application but is there...

DRY code using Rspec matchers

I want to improve the following block of code to be more readable/concise/DRY (my actual arguments are a bit more complicated to #have_css): negate ? expect(page).to(have_css('selector', text: 'text')): expect(page).to_not(have_css('selector', text: 'text')) Is there anyway to store 'selector', text: 'text' in a variable to be reused as method arguments? Or alternatively...

Can rspec be used to feature test an integrated rails-angular app?

I have a very basic, integrated rails-angular app. It just renders a link, which uses data from a get request to rails: 'use strict'; angular.module('angularRspec.controllers') .controller('FightersController', function($scope, $http){ console.log("FightersController is loaded..."); $scope.fighters = []; $http.get('./fighters.json'). success(function(data, status){ $scope.fighters = data; console.log(status); console.log(data); }). error(function(data, status, headers, config) { console.log(status); console.log(headers);...

Passing Two Parameters on a JSON POST Request in Rspec

I have a JSON Rails 4 API that I'm testing with Rspec. I'm having trouble passing to two parameters in the post :create request. Here is the current test: require 'spec_helper' module Api module V1 describe Api::V1::ProductsController, type: :controller do before do @api_app = FactoryGirl.create(:api_app, request_origin: "") @store = FactoryGirl.create(:store)...

stubbing 'gets' in ruby multiple times

I have a simple question asking Ruby script: def ask question while true puts question reply = gets.chomp.downcase return true if reply == 'yes' return false if reply == 'no' puts 'Please answer "yes" or "no".' end end puts(ask('Do you like eating tacos?')) I'm testing it like this describe 'ask'...

Rspec test public controller method passing params to private controller method

This is my controller: class PlansController def use_new_card @user = User.find_by_id(new_card_params[:user_id]) if new_stripe_card ... end private def new_card_params params.permit(:user_id, :stripeToken) end def new_stripe_card{user_id:, customer_id: @user.stripe_customer_id, source: new_card_params[:stripeToken]}).new_card end end I'm trying to write a controller spec that tests that when the proper parameters are POST to the use_new_card...

Testing an RSpec mock that is called twice

I have a validation module that I include in my controllers. In my controllers for Admin actions they all inherit from an AdminController which calls require_permission :admin before each to make sure the current user is an admin. In another one of my controllers I call require_permission? :view_admins to verify...

If I stub out .save method in my controller test how can I check the correct show template is rendered?

I am trying to test a controller create method in a rails app using RSpec as shown below: def create @user = if redirect_to user_path( else render new_user_path flash[:error] = "User not saved" end end However if i stub out .new to prevent the test from using Active...

How to stub a class method using rspec/rspec-mocks

I am using rspec-mock for test-driven-development. I am starting implementing a single class and mocking/stubbing the other classes using rspec-mock. Mocking objects of classes yet to be implemented works well. However when I try to mock a class method of a class that does not exist yet, I haven't been...

RSpec 3 - Test controller action that does not have routes

I have a controller and there is an action within that controller. That action contains only a few lines of code and this method doesn't have any routes, as follows: class MyController < ApplicationController def action_a # an action does have routes ..some code.. end def action b #(an action...

Using external variable in rspec-puppet test

Have some stuck with using variable in rspec. Here is my params.pp case $::osfamily{ Debian: { $ssh_daemon = "ssh" } Redhat: { $ssh_daemon = "sshd" } In rspec test i need to use variable $ssh_daemon, like this it { should contain_service("${ssh_daemon}").with( :ensure => 'running', :enable => 'true', )} Here is...

How to map browser dialog using capybara/selenium

What is the best way to handle browser dialogs (with ok/cancel buttons) using capybara/selenium? The way I found easiest is by running the following: dialog = page.driver.browser.switch_to.alert dialog.accept Any thoughts for a better approach? Whoever downed this post please give a valid reason... it's not helpful to down vote with...

Switch between windows with frames

I have main window with frames and a popup where I do some operations: within_frame("MainFrame") do find("btnNewItem").click #opens popup window end within_window(windows.last) do within_frame("frmFrame2"){ some_operations find("btnOK").click #closes a popup } end within_window(switch_to_window(windows.first)) do within_frame("MainFrame") do find("btnDeleteItem").click #deletes item accept_popup_dialog end end But when operations are done in popup window and...

Why spec does not see the class in the module?

I trying to test my app, and when I do this spec/support/devise_models.rb module DeviseModels class UserWithCustomEncryption < User protected def password_digest(password) password.reverse end end end spec/rails_helper.rb RSpec.configure do |config| config.include DeviseModels ... and when I call in my spec shell show me an error NameError: uninitialized constant UserWithCustomEncryption and...

Cannot run elastic search in circleci to make my rspec for elasticsearch to pass?

i have configured my project in github with circleci. I am using searchkick for elastic search. my code to reindex looks like this: IN spec_helper.rb RSpec.configure do |config| .... config.before :each do Location.reindex end ... end My app/models/location.rb looks like this class Location < ActiveRecord::Base ... searchkick word_start: [:location_name], autocomplete:...

NoMethodError undefined method sign_in rspec devise

Given that I am trying to write a simple rspec test whilst using devise I seem to keep NoMethodError: undefined method sign_in I have the following setup but cannot seem to get around this. I did come across another similar question to this Rails, Devise, Rspec: Undefined method 'sign_in' and...

Is element visible?

I have an error when I try to check if some element is visible. My method is the following: if find(:xpath, "//td[text()='#{subtab}']").visible? find(:xpath, "//td[text()='#{subtab}']").click else find(:xpath, "//td[text()='#{tab}']").click find(:xpath, "//td[text()='#{subtab}']").click end In if find(:xpath, "//td[text()='#{subtab}']").visible?, I have: Capybara::ElementNotFound: Unable to find xpath "//td[text()='Plan List2']" but when the element is correctly visible,...

What is the difference between User.make and

In Capybara docs, it has describe "the signin process", :type => :feature do before :each do User.make(:email => '[email protected]', :password => 'password') end it "signs me in" do visit '/sessions/new' within("#session") do fill_in 'Email', :with => '[email protected]' fill_in 'Password', :with => 'password' end click_button 'Sign in' expect(page).to have_content 'Success' end...