rspec,capybara,rspec-rails , Rspec/Capybara features tests not running, even with _spec.rb ending


Rspec/Capybara features tests not running, even with _spec.rb ending

Question:

Tag: rspec,capybara,rspec-rails

When I run my Rspec feature examples, they are not being detected. When I specify the route to my /features folder, the message I get is " No examples found". I'm not sure if it's a requirement issue or something I'm missing with my test.

my feature test:

require "rails_helper"
require 'capybara/rspec'



feature "user creates student", :type => :feature do
background do
    user = create :user
scenario "with valid data" do
    visit '/students/new'
    within("form") do
        fill_in ":first_name", :with => 'jason'
        fill_in ":last_name", :with => 'foobar'
        fill_in ":user_id", :with => '1'
    end
    click_button 'Submit'
    expect(page).to have_content 'jason foobar'

  end
end


  feature "user cannot create student" do
   background do
    user = create :user
    scenario "with invalid data" do
    visit '/students/new'
    within("form") do
        fill_in ":first_name", :with => :nil
        fill_in ":last_name", :with => 'foobar'
        fill_in ":user_id", :with => '1'
    end
    click_button 'Submit'
    expect(studnt.errors[:first_name]).to include("can't be blank")

  end
end
 end


 end

Answer:

Your spec is getting run, but because it is malformed, there are no examples in it.

If you were to format it properly (e.g. in terms of indentation), it would be more clear, but your background blocks include both of the associated scenarios.

You need to delete the last two end statements in your file and insert end statements at the end of each background, as follows:

require "rails_helper"
require 'capybara/rspec'

feature "user creates student", :type => :feature do
  background do
    user = create :user
  end

  scenario "with valid data" do
    visit '/students/new'
    within("form") do
      fill_in ":first_name", :with => 'jason'
      fill_in ":last_name", :with => 'foobar'
      fill_in ":user_id", :with => '1'
    end
    click_button 'Submit'
    expect(page).to have_content 'jason foobar'
  end
end

feature "user cannot create student" do
  background do
    user = create :user
  end

  scenario "with invalid data" do
    visit '/students/new'
    within("form") do
      fill_in ":first_name", :with => :nil
      fill_in ":last_name", :with => 'foobar'
      fill_in ":user_id", :with => '1'
    end
    click_button 'Submit'
    expect(studnt.errors[:first_name]).to include("can't be blank")
  end
end

Related:


How to remove entries using a model function?


ruby-on-rails,rspec
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...

Capybara::ElementNotFound radio by id


ruby-on-rails-4,capybara
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...

How to map browser dialog using capybara/selenium


ruby,selenium,capybara
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...

Why spec does not see the class in the module?


ruby-on-rails,rspec
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 UserWithCustomEncryption.new shell show me an error NameError: uninitialized constant UserWithCustomEncryption and...

Faking instance variable in RSpec and Capybara feature spec


ruby-on-rails,ruby,rspec,capybara
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...

Rspec view test with url parameters


ruby-on-rails,unit-testing,testing,rspec,rspec-rails
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 diagnose slow rails / rake / rspec tasks


ruby-on-rails,ruby,rspec,rake,rakefile
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...

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


ruby-on-rails,ruby,rspec
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...

Passing Two Parameters on a JSON POST Request in Rspec


ruby-on-rails,ruby,json,post,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: "0.0.0.0") @store = FactoryGirl.create(:store)...

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


ruby-on-rails,ruby,rspec,factory-girl
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...

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


ruby-on-rails,ruby,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...

Specific test behaviour for ruby gem — mocking sleep


ruby,rspec,gem
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...

Using external variable in rspec-puppet test


ruby,rspec,puppet
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...

Replace fixtures with factory girl in for generated scffold test cases


ruby-on-rails,rspec,factory-girl
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 FactoryGirl.build(:model) Test cases fails for GET #index assigns all tag_menus as @tag_menus DELETE #destroy destroys the requested...

How to set text into Summernote textarea with Capybara + Poltergeist


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

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


ruby-on-rails,ruby-on-rails-4,rspec,rspec-rails,stub
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...

Not able to run rspec with Sequel


ruby-on-rails-4,rspec,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.

RSpec 3 - Test controller action that does not have routes


ruby-on-rails,ruby-on-rails-4,rspec,controller,rspec3
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...

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


ruby-on-rails,angularjs,rspec,capybara
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);...

RSpec test for rake task


ruby-on-rails,ruby,rspec,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...

how to add template file in rspec-puppet


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

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


ruby-on-rails,ruby,rspec,capybara
I am trying to test a controller create method in a rails app using RSpec as shown below: def create @user = User.new(user_params) if @user.save redirect_to user_path(@user.id) 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...

NoMethodError undefined method sign_in rspec devise


ruby-on-rails,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...

Switch between windows with frames


ruby,capybara
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...

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


ruby-on-rails,ruby,ruby-on-rails-4,rspec,rspec-rails
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...

Route Not Working in Rspec


ruby-on-rails,rspec,routes
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...

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


ruby-on-rails-3,github,rspec,elasticsearch,circleci
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:...

Rspec can't stub where or find_by_, only find


ruby-on-rails,ruby-on-rails-4,rspec,rspec-rails,stub
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!...

model's class trying to access database even using double


ruby-on-rails,ruby-on-rails-4,rspec,rspec-rails
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...

Using validate_presence_of with strict validations


ruby-on-rails,ruby,rspec,shoulda
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...

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


ruby,rspec,mocking
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 test public controller method passing params to private controller method


ruby-on-rails,ruby-on-rails-4,rspec,controller,rspec-rails
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 StripeService.new({user_id: @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...

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


ruby-on-rails,ruby,rspec,devise
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 User.new(password: same_as_created_user).encrypted_password but the passwords generated do not match....

Trouble in RSpec test - saving parent record twice


ruby-on-rails,ruby-on-rails-4,activerecord,rspec,nested-attributes
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: Factory Girl & Complex Associations


ruby-on-rails,ruby,rspec,tdd,factory-girl
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...

What is the difference between User.make and User.new?


ruby-on-rails,unit-testing,rspec,capybara
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...

DRY code using Rspec matchers


ruby,rspec
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...

Rspec routing test not passing


ruby-on-rails,ruby,rspec
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")...

RSpec controller test error: controller does not implement method


ruby-on-rails,ruby-on-rails-4,rspec,devise
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...

stubbing 'gets' in ruby multiple times


ruby,rspec
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'...

Run block once before all capybara tests


ruby-on-rails,ruby,rspec,capybara
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...

Is element visible?


ruby,capybara
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,...

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


rspec,sidekiq
I have a block: def already_syncing? Sidekiq::Queue.new(queue_name).any? { |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....

Testing an RSpec mock that is called twice


ruby-on-rails,ruby,unit-testing,rspec
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...