FAQ Database Discussion Community


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

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

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

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

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 matcher that checks collection to include item that satisfies lambda

ruby,rspec,rspec-rails,rspec3
I am a bit at a loss as to how to write a RSpec 3.2.x spec that checks wether a list contains at least one item that satisfies a condition. Here is an example: model = Invoice.new model.name = 'test' changes = model.changes expect(changes).to include { |x| x.key == 'name'...

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

`allow_any_instance_of` mock not working in scope

ruby-on-rails,ruby,rspec
My mock is only working when it's in the before block shown below. This is just my quick and dirty representation of my problem. Literally when I move the line from the before block to the does not quack assertion, it stops mocking :( describe 'Ducks', type: :feature do before...

How to insert an attribute into rspec test for validation messages using i18m

ruby-on-rails,rspec
I have my translations file setup with some custom error messages for some ActiveRecord validations, although when I pass an %{attribute} into it, the test fails. How do I get the rspec test to use the translation? en.locale en: activerecord: errors: models: account: attributes: name: invalid: "%{attribute} must only include...

rails/rspec how to get the response when making a post request with body to API?

ruby-on-rails,rspec
I'm building a Rails backend API and i have a controller that receives post requests. I'm using rspec to make a call to the endpoint and so far it looks like it working. However i am unable to visualise my response. (the controller works and renders the correct JSON). My...

boolean methods in ruby on rails

ruby-on-rails,ruby,rspec
# As a user, you can initialize the guessing game with a number, which is the correct guess # so the initialize method takes in one parameter, and sets game_complete? to false # # As a user, I can guess the number, which will # return :too_high if its >...

Rspec and Rails NoMethodError for comparison operator

ruby-on-rails,ruby,rspec,factory-girl
I am testing a User model with the following spec: require 'rails_helper' require 'spec_helper' RSpec.describe User, type: :model do it "password length to be equal to or greater than 8 characters" do expect(FactoryGirl.build(:user, password: '12345678')).to be >= 8 end end The Factory looks like this: require 'faker' FactoryGirl.define do factory...

Watir Rspec Ruby : Comparing new/edited value with old/previous value

ruby-on-rails,ruby,rspec,watir,rspec-rails
Auto generated name twice, first $name = generate_name self.name = $name produces: $name is "Abc" And then edited the $name to be "Xyz". Which causes the previous/old name to be no longer available/saved in the app, its overwritten by new/edited name. I now have to compare the two values of...

Rails validate format. “001” should be valid but not “1” or 1. /\A\d\d\d\z/ not working

ruby-on-rails,regex,rspec,shoulda
I have been running into an issue when trying to test the following validation in one of my models: validate :clientnumber, format: { with: /\A\d\d\d\z/ } Essentially I want to allow "001" to be a valid entry, but not allow "1". When I run these tests: it do should allow_value('880',...

array push pop in ruby

ruby,rspec
This is my main code. I am using rspec require_relative "rpn_calculator" describe RPNCalculator do let(:calculator) {RPNCalculator.new} it "adds two numbers" do calculator.push(1) calculator.push(3) calculator.plus expect(calculator.value).to eq 4 end And this is my code in rpn_calculator class RPNCalculator @arr=[] @ans=0 def push(val) @arr.push(val) end def plus while @arr.size>=1 do @[email protected][email protected] end...

How to create a Gemfile?

ruby,rspec
How to create a Gemfile? I am trying to follow a tutorial (RSpec Tutorial) that says below:- and I am not able to do it. I am totally new to Ruby. Thanks in advance. Here's a basic Gemfile to start with. source 'http://rubygems.org' gem "rspec" Rspec tutorial link: http://www.tweakstreet.io/blog/2015/2/9/using-standalone-jruby-and-rspec-to-test-your-java-projects...

Testing Rails app with RSpec and Capybara

ruby-on-rails,rspec,capybara
In testing my rails app (using RSpec and Capybara) I am having troubles testing AngularJS functions (from the Users point of view). Can I not test with only RSpec and Capybara or do I also need something like protractor? any help would be great! thank you!...

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

How to stub Time.now.hour

ruby-on-rails,testing,time,rspec,stubbing
I have a helper method which outputs a greeting #{greet(Time.now.hour)} in the view pending the time of day: users_helper.rb: def greet(hour_of_clock) if hour_of_clock >= 1 && hour_of_clock <= 11 "Morning" elsif hour_of_clock >= 12 && hour_of_clock <= 16 "Afternoon" else "Evening" end end And I am trying to test this...

Unable to locate nested p element

ruby-on-rails,rspec,watir,watir-webdriver,page-object-gem
How would I locate the "tile" element in the HTML: <div class="con-head"> <div class="up-at js-con-dates"> <span class="bold">Last date</span> 7:13 PM <br> <span class="bold">Save</span> 7:12 PM </div> <p class="tile">Text: Kids </p> <p class="desc js-desc" style="">Q&A </p> </div> I tried to locate it with the accessor: div(:my_title) { div_element(:class => 'con-head').div_element(:class =>...

Get environment variable from other proccess in Ruby

c#,ruby,rspec
I have the following task: in my C# code I'm running server with random port and adding this port to EnvironmentVarables via Environment.SetEnvironmentVariable("PORT", Convert.ToString(Fixture.Uri.Port)); And after that I have to get this PORT variable from Ruby rspec code to tell tests what port it should use. Is there any ways...

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

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

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

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 testing find_or_create method

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

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 test failing on expect(user.save).to be_true

ruby-on-rails,rspec
Using rails 4.1.8 and rspec 3.2.1 This test passes in other applications where my rspec gem is 2.0. It also works in development mode just fine. If I create a user with an email in all caps, it get saved in the database as lowercase. This is my fail message:...

where to put config for turnip step definitions

ruby-on-rails,ruby,rspec
I am trying to build testing capability for my rails application. I am using turnip to write feature test. In the github page, it is said that after putting the step definitions in a module "You can now include this module in RSpec". But it is not clear where the...

Can I alias a nested RSpec matcher?

ruby,rspec,rspec3,rspec-expectations
I have several RSpec examples that share the following complex expectation, with the array records and the floating point numbers min_long, max_long, min_lat, max_lat varying between these examples. expect(records).to all have_attributes( shape: have_attributes( exterior_ring: have_attributes( points: all( have_attributes( longitude: be_between(min_long, max_long), latitude: be_between(min_lat, max_lat) ) ) ) ) ) (The...

Rubocop RSpec Describes are failing

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

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

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

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

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

Difference between let and def

ruby,rspec
I wonder between method and let definition inside rspec describe block? Why should I use let instead def? let(:create_user) { post :create} Vs def create_user post :create end Both ways seems to work the same inside the test: expect {create_user}.to change { User.count }.by(1) ...

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

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

In RSpec, how to determine the time each spec file takes to run?

rspec
Background: My project's continuous integration build runs RSpec in several parallel runs. Specs are partitioned across parallel runs by spec file. That means long spec files dominate test suite run time. So I want to know the time each spec file takes to run (not just the time each example...

Testing my rake task - Rails 4

ruby-on-rails,ruby,ruby-on-rails-4,rspec
Hoping someone can point out what I'm doing wrong here, as I cant get my rake task test to pass, it seems that after the rake task has run I lose my instance variable as it returns nil where as before the rake task is run i get a record...

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

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

TypeError: wrong argument type class (expected module) in rspec

ruby,rspec,tdd
i'm developing a simple net application (packed as a gem) to learn Ruby and TDD. I have this class (receiver.rb): require 'eventmachine' class Receiver < EM::Connection def initialize(port) EM.run do EM.open_datagram_socket('0.0.0.0', port, self) end end end And this test (receiver_spec.rb): require "spec_helper" require "net/receiver" describe "Receiver" do it "can istantiate"...

Testing destroy method failure in Controller test

ruby-on-rails,rspec
I have a controller which destroys an item in my db. Currently it looks like this: before_filter(:except => :toggle_item_owned_state) do @collection = current_user.collections.find(params[:collection_id]) end def destroy @item = @collection.items.find_by_id(params[:id]) if @item.destroy redirect_to collection_items_path(@collection) else flash.now[:alert] = "There was a problem deleting this item." redirect_to root_path end end Now, I've written...

Rspec: let does not work

ruby-on-rails,ruby,rspec
I have some Rspec tests, where I'm initialising variables with let: describe 'methods' do let(:order) { Order.new } let(:event_1) { FactoryGirl.create(:event) } let(:event_2) { FactoryGirl.create(:event) } context 'should checks if any event is paid' do order.events << event_1 order.events << event_2 order.events_paid?.should == true end context 'should write aasm state'...

Rspec controller tests broken after switch to postgresql

ruby-on-rails,postgresql,rspec
I've originally been using SQLite with rspec without issue. However, since my production environment uses postgresql, I have changed rspec to use postgresql. I am now getting errors that look like: undefined method `models' for nil:NilClass From what I can tell, model tests are still working fine whereas my controller...

How can I stub a controller instance variable using RSpec?

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

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 can I stub a dependency in a Rails service

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

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

Setting a session value through RSpec

ruby-on-rails,ruby,session,rspec
My current code looks like this: /spec/support/spec_test_helper.rb module SpecTestHelper def login_admin user = FactoryGirl.create(:user, type: 0) session[:user_id] = user.id end end /app/controllers/application_controller.rb def current_user if session[:user_id].nil? render plain: 'Error', status: :unauthorized else @current_user ||= User.find(session[:user_id]) end end Unfortunately, session is always empty in the current_user method. Is there a way...

How to configure RSPEC to never run on RAILS_ENV production

ruby-on-rails,ruby,rspec
I was trying to run some test because of changes I did...so I ran RAILS_ENV=production bundle exec rspec which was something very stupid to do since rspec (the tests) were configured to truncate all the tables and this was exactly what happened on PRODUCTION !! and you can imagine the...

How to disable a before_action in a controller spec?

ruby-on-rails,ruby-on-rails-4,rspec,rspec-rails
I've employed the use of this in my controller spec: controller.class.skip_before_action Specifically, in this case: controller.class.skip_before_action :require_authorisation_to_view_materials MaterialsController: class MaterialsController < ApplicationController before_action :set_material, only: [:show, :edit, :update, :destroy] before_action :require_authorisation_to_view_materials, only: [:index, :show] def require_authorisation_to_view_materials # For Materials Page unless user_signed_in? &&...

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

Wait for Websocket Rails event to finish in test environment

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

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

Dynamic expectations in Rspec

ruby-on-rails,ruby,testing,rspec,tdd
I am trying to test a dynamic url path through an Rspec expectation, as below: describe 'registering a user' do context 'with valid data' do it 'confirms user registration' do visit '/users/new' fill_in 'Name here...', with: 'johnny bloggs' fill_in 'Your email here...', with: [email protected]' click_button 'Notify me' expect(current_path).to eq [email protected]'...

RSpec Rails wont find my meta tags

ruby-on-rails,rspec,meta-tags
I am just writing a couple of test and I want to make sure that I can test that some meta tags are on the page. describe "article", :type => :feature do it "has correct meta tags", js: true do love_article = FactoryGirl.create(:love_article, title: 'Kitten Takes Over the World!', created_at:...

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

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

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 having difficulty testing #create with build controller method

ruby-on-rails,ruby,rspec
So if your #create controller method is simply: @testimonial = Testimonial.new(testimonial_params) And you test it in your specs like so: testimonials_controller_spec.rb describe "POST #create" do context "with VALID attributes" do it "creates new testimonial" do expect { post :create, testimonial: FactoryGirl.attributes_for(:testimonial) }.to change(Testimonial, :count).by(1) end end end It works fine....

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

Where is the webkit_debug log located?

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

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

How to test ransack output? Rspec

ruby-on-rails,ruby,rspec,ransack
I`ve got a little problem here and hope you help me. I have a list of hotels in the table. Here is a view: <% provide(:title, 'List of hotels') %> <h1>List of hotels</h1> <table> <tr> <th><%= sort_link @search, :name, "Name" %></th> <th><%= sort_link @search, :breakfast, "Breakfast" %></th> <th><%= sort_link @search,...

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

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

rspec controller empty session

ruby-on-rails-3,testing,rspec,controller
app/controllers/new_controller.rb: class NewController < ApplicationController def enter_time session[:dr] = 'dr' if !params[:time].nil? then Time.zone = @franchise.time_zone inanhour = 1.hour.since(Time.zone.now) delivery_time = delivery_time_format(params[:time]) delivery_time = delivery_time.change(offset: (Time.zone.now.utc_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...

controller is Nil in rspec test

ruby-on-rails,ruby,rspec
I have following RSpec test: require 'rails_helper' require 'spec_helper' RSpec.describe "Users", type: :request do describe "sign in/out" do describe "success" do it "should sign a user in and out" do attr = {:name=>"Test1", :email => "[email protected]", :password => "foobar", :password_confirmation => "foobar" } user = User.create(attr) visit signin_path fill_in "Email",...

Problems installing RSpec

ruby-on-rails,rspec
I am currently trying to teach myself how to use rspec testing with rails. I was following the guides from the blog here, http://everydayrails.com/2012/03/12/testing-series-rspec-setup.html and came to the point where i was unable to run the command "rails g rspec:install" I wind up getting a whole host of issues being...

Rails 4: Factory Girl & Rspec with associated Model

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

rails after_create not updating parent model

ruby-on-rails,ruby,rspec
Using the same approach obtained from this solution: Use both Account and User tables with Devise I am trying to update an owner_id column on the Account model, after the User has been saved: Account Model class Account < ActiveRecord::Base has_many :users has_secure_token accepts_nested_attributes_for :users validates :name, :presence => true...

lazy evaluation and rspec's let method

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

Capybara - Determine if selector count has changed

ruby,rspec,capybara
I am writing a test to confirm that hidden (Note: not destroyed. They are hidden using a boolean DB field) items no longer show up on my page. I know with Capybara I can use the following to confirm a selector's count: expect(page).to have_selector('input', count: 12) Is it possible to...

undefined method `before' for main:Object

ruby,rspec,serverspec
I'm getting the above error from section of code below. What is the cause? 1 require 'spec_helper' 2 3 before(:all) do 4 puts "ServerSpec tests on #{ENV['TARGET_HOST']}" 5 end Full error: /home/newatson/src/serverspec/spec/cfengine3/common_spec.rb:3:in `<top (required)>': undefined method `before' for main:Object (NoMethodError) from /home/newatson/.gem/ruby/1.9.1/gems/rspec-core-3.2.3/lib/rspec/core/configuration.rb:1226:in `load' from /home/newatson/.gem/ruby/1.9.1/gems/rspec-core-3.2.3/lib/rspec/core/configuration.rb:1226:in...

RSpec fails upon a namespaced model assigned to blog

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

argument error in Ruby

ruby-on-rails,ruby,rspec
I have this code require_relative 'die' describe Die do describe '#initialize' do it 'expects a single argument' do expect(Die.instance_method(:initialize).arity).to eq 1 end it 'raises ArgumentError if sides are < 1' do expect { #####line 10 Die.new(-1) }.to raise_error(ArgumentError) expect { Die.new(0) }.to raise_error(ArgumentError) end end I am getting the following...

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

How can I expect that a certain method is called with a specific block?

ruby-on-rails,ruby,rspec,mocking
I want to be able to test with rspec that a specific gem called with a specific block: The code looks like this SomeGem.configure do |config| config.username = "hello" config.password = "world" end and the spec that I have written looks like this: it 'sets valid gem configuration' do credentials...

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

Error “undefined method `<' for nil:NilClass” when testing a model with RSpec.

ruby-on-rails,ruby-on-rails-4,rspec,rspec3
I am learning RSpec and testing the below scenario: require 'rails_helper' RSpec.describe Student, type: :model do before(:each) do Student.delete_all end it "roll number can't be less than 0 or more than 80" do s = Student.create(:name => "sanjay" , :lastname => "test" , :roll => 0) s1 = Student.create(:name =>...

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

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

Logging for rspec selenium/capybara tests running in Browserstack

ruby,selenium,rspec,capybara,browserstack
I am building a set of automated regression tests in ruby using rspec and capybara. To give you an idea of a test, imagine logging in to a website, adding a new data item with all of its fields, saving it, validating the new row, updating the row, changing fields,...

How to continue a seeded RSpec run?

rspec
Is there a way to restart a seeded RSpec run from a particular point, rather than from the beginning? When making a change that potentially affects all files (e.g., removing Bundler.require) in a large code-base, I want to run a full set of RSpec tests, fix the first error, then...

Rails test JS view from controller spec

javascript,ruby-on-rails,ruby-on-rails-4,rspec
I've got a controller action that responds with a js response. This js response actually renders another partial. I'd like a controller test in case the partial or js file ever has an error. controller: class ZonesController < ApplicationController def library_zones end end library_zones.coffee: $("#zoneSelectionPlaceholder").html("<%= j(render 'library_zones') %>") _library_zones.html.haml (notice...

Can RSpec be configured to fail any example which does not contain any expectations?

ruby,rspec
I know that in RSpec you can easily mark an example as incomplete by omitting the block: it 'is not a complete example' But is it possible to get RSpec to fail any example which does not contain any expectations? IE. RSpec will happily pass this example: it 'does not...

How can I write factories for Models that validate each other?

ruby-on-rails,ruby-on-rails-4,rspec,factory-girl
Parent Class: class Parent < ActiveRecord::Base has_many :kids validates_presence_of :kids end Kid Class: class Kid < ActiveRecord::Base belongs_to :parent, inverse_of: :kids validates :parent, presence: true end Parent Factory: FactoryGirl.define do factory :parent do 2.times do parent.kids << FactoryGirl.create(:kid) end end end Kid Factory: FactoryGirl.define do factory :kid do parent end...

Capybara testing with jQuery, Bootstrap, and jQuery-ui from CDN

jquery,ruby-on-rails,rspec,capybara,bootstrap
I am getting jQuery, jQuery-ui, and Bootstrap from CDNs in my app. Since I switched over to using CDNs instead of gems, I am getting errors in my specs that they can't find $. Is there a way to download a copy of these scripts and have my specs use...

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: execute the same expectation under different circumstances

rspec
I want to make sure that an element on my website is only displayed when logging in. This is how I achieve it at the moment: it 'displays statistics when logged in' do expect { login_as(create :user) refresh_page }.to change { page.has_content? 'Statistics' }.from(false).to true # I know, "to true"...

Why Rails instance method can be used as class method in rspec

ruby-on-rails,ruby,ruby-on-rails-3,rspec,actionmailer
I found a snippet in an article about sending mails in a Rails application: class ExampleMailerPreview < ActionMailer::Preview def sample_mail_preview ExampleMailer.sample_email(User.first) end end in this link: http://www.gotealeaf.com/blog/handling-emails-in-rails. I do not know why the method: sample_email(), which in my mind should be an instance method, can be accessed like class method...

Testing tools available for Rails application [closed]

ruby-on-rails,ruby,rspec
I am newbie to rails testing I google and found few testing framework like 1. rspec 2. cucumber 3. capybara 4. factorygirl 5. jasmin and default rails has its own testing tools. I need to know what to use and when to use for functional, unit and integration testing And...

Rspec testing (can't tell whether a certain line of code is getting executed)

ruby-on-rails,rspec
I tried testing this method in rspec: def resend_if_failed ResendWorker.new(self).resend_message end How do I test that ResendWorker.new(self).resend_message gets executed? ...

Avoid excessive rspec nesting with subject, let, and alternative arguments

ruby-on-rails,ruby,rspec
I'm trying to do some model_spec testing but having trouble with not having to further nest my rspec code. It would be great if in this case, I could just have a set of "it's" instead of having to add context everytime I want to switch the variable var. Here's...

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

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