rspec,rspec2 , how to transform old rspec-syntax “it { should_not be_valid }” to rspec2?

how to transform old rspec-syntax “it { should_not be_valid }” to rspec2?


Tag: rspec,rspec2

transform from old rspec syntax to the new one:


 describe "when password is not present" do
    before { @user.password = @user.password_confirmation = " " }

    it { should_not be_valid }

How should the it-part looks like with the newer expect-syntax?


Using the expect-syntax the test would be:

it { is_expected.not_to be_valid }

Note that for the one-liner syntax, the should-syntax is still supported (ie no deprecation warning) so you do not have to make any changes. From the Relish page on RSpec Core 3.1:


How can I stub a dependency in a Rails service

I have: a web service wrapper that calls a 3rd party API (lib) a service that calls that wrapper and does some finagling (service) Testing the lib class with VCR works great, but I am not sure how to test the service. Specifically, how can I stub the API call...

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

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

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

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

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

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

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

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

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

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

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.

lazy evaluation and rspec's let method

I am reading the book The Rails 4 Way, and I am learning about Rspec. I know that lazy evaluation is when the expression is not evaluated until it is used, whereas eager evaluation is where the expression is evaluated immediately. let uses lazy evaluation, where the expression in the...

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

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

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

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

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

Wait for Websocket Rails event to finish in test environment

I am using the Websocket Rails gem in my Rails application to send an event that triggers a refresh of part of the page. All is working fine, but in my testing (I am using Rspec + Capybara + Selenium) I can't seem to find a way to wait for...

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

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

RSpec fails upon a namespaced model assigned to blog

I was doing the RSpec testing with Rails and it's failing due to the namespaced model that I assigned to its associations of the model. CLI: Failures: 1) Blog::BlobsController GET index assigns all blog/blobs as @blobs Failure/Error: expect(assigns(:blog::blobs)).to eq([blog::blobs]) NoMethodError: undefined method `blobs' for :blog:Symbol # ./spec/controllers/blog/blobs_controller_spec.rb:8:in `block (3 levels)...

Rspec testing find_or_create method

I've checked my simplecov result and I've seen that record = User.where("fb_id = ? or email = ? ", params[:fb_id], params[:email]).first_or_create do |rows| rows.first_name = params[:first_name] rows.last_name = params[:first_name] etc(all the variables after do |rows| ) haven't covered. Any ideas, how could I test this stuff ? ...

Rubocop RSpec Describes are failing

Actually i'm trying to fix that issues: Do not use multiple top level describes - try to nest them. The first argument to describe should be the class or module being tested. I have eight tests in that format: describe 'PublicanCreatorsCreate.init_docu_work' do it 'accesses a directory and creates there an...

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

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

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

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

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

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

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

rspec controller empty session

app/controllers/new_controller.rb: class NewController < ApplicationController def enter_time session[:dr] = 'dr' if !params[:time].nil? then = @franchise.time_zone inanhour = 1.hour.since( delivery_time = delivery_time_format(params[:time]) delivery_time = delivery_time.change(offset: ( / 3600).to_s) session[:target_time] = [delivery_time, inanhour].max.to_s end end end spec/controllers/new_controller_spec.rb: require 'spec_helper' describe NewController, :type => :controller do...

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 can I stub a controller instance variable using RSpec?

new_controller_spec.rb require 'spec_helper' describe NewController do describe 'actions' do describe 'POST /franchise_opportunities' do it 'renders v3/franchise_opportunities when domain id 5' do domain = double(Domain, mrdeliverycom?: true) controller.instance_variable_set(:@domain, domain) post :franchise_opportunities, name: 'v' response.should render_template('v3/franchise_opportunities') end end end end new_controller.rb # -*- encoding : utf-8 -*- class NewController < ApplicationController before_filter...

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

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

Where is the webkit_debug log located?

I am working on transitioning from the default rack_test driver to the webkit driver so I can run javascript in my rspec tests. Unfortunately, I am getting session timeout errors, so I changed my driver to webkit_debug, however, I can't seem to find the webkit_debug log file for the life...

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

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

Rails 4: Factory Girl & Rspec with associated Model

I previously fixed an issue with some code that works though it is a little ugly. Problem now is that it breaks my tests! The idea here is that I can create a Campaign and associate 1 zip-file and one-to-many pdfs. Previous question and solution: Rails 4.2: Unknown Attribute or...

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

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

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

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

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

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

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