Menu
  • HOME
  • TAGS

How to test ransack output? Rspec

ruby-on-rails,ruby,rspec,ransack

A test normally has three phases: setup, execute, assert. The setup phase would be to create some hotels, which have different properties for the aspect you are testing. The execute phase would be to click on the link which sorts the hotels. The assert phase would be to inspect the...

Route Not Working in Rspec

ruby-on-rails,rspec,routes

It looks like you have a controller test (as opposed to an integration test). If that's the case then the second one fails because controller tests bypass the routing and instead need to be told which action method to call with a post (or get or put or delete) instead...

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

RSpec provides no special mechanisms to access elements under test, so yes, you would need to somehow stub the id method and have it return whatever you wish (e.g. 1). To do that, you must have a way to access the event object in your test so that you can...

Rspec and Rails NoMethodError for comparison operator

ruby-on-rails,ruby,rspec,factory-girl

your password should be >= 8 not the user object so it should be something like this expect(FactoryGirl.build(:user, password: '12345678').password.to_s.length).to be >= 8 ...

rspec controller empty session

ruby-on-rails-3,testing,rspec,controller

Try: expect(session['dr']).to eq("dr"). session values are separate from assigns....

Unable to locate nested p element

ruby-on-rails,rspec,watir,watir-webdriver,page-object-gem

In the HTML, the element with class "tile" is actually a p element: <p class="tile">Text: Kids </p> As a result, you need to locate it using the paragraph_element method instead of the div_element method: div(:my_title) { div_element(:class => 'con-head').paragraph_element(:class => 'tile') } ...

boolean methods in ruby on rails

ruby-on-rails,ruby,rspec

It looks like you aren't initializing the subject, unless there is more code that you are not showing. Here is a version that works: class GuessingGame def initialize(num) @num = num end def guess(num) if num < @num return :too_low elsif num > @num return :too_high else return :correct end...

RSpec fails upon a namespaced model assigned to blog

ruby-on-rails,ruby-on-rails-4,rspec

Your test says: blobs = Blog::Blob.create! This is confusing, because blobs is plural, but you're only creating one blob. So start by renaming that to blob. Then expect(assigns(:blog::blobs)).to eq([blog::blobs]) should be expect(assigns(:blobs)).to eq([blob]). In the index action, you set @blobs = Blog::Blob.all. The assigns correspond to the controller's instance variables....

Rspec can't stub where or find_by_, only find

ruby-on-rails,ruby-on-rails-4,rspec,rspec-rails,stub

Ok I have a temporary solution, which is just to use select. I.e., #run code @current_plan = Plan.select { |p| p.stripe_subscription_id == event.data.object.lines.data.first.id }.first #test code @plan = Plan.new Plan.stub_chain(:select, :first).and_return(@plan) #result of @current_plan (expecting @plan) => @plan Still though... if others have thoughts please chime in... I'm now a...

Testing an RSpec mock that is called twice

ruby-on-rails,ruby,unit-testing,rspec

The best way, IMO, would be to wrap all your admin-authenticated tests in a context which expect the :admin call. describe MyController do context "when authenticated" do before do expect(controller).to receive(:require_permission).with :admin end it 'requires view_admins permission' do expect(controller).to receive(:require_permission).with :view_admins get :admins end end end If you don't want...

RSpec test for rake task

ruby-on-rails,ruby,rspec,rake-task

A couple things. First off, you should put created_at in the create method: user.items.create(description: "Old Item", created_at: 12.days.ago). Second, you need to call user.reload in order for the changes from your rake task to be available. So it should look like this: user.reload expect(user.items.count).to eq 1 etc...

stubbing 'gets' in ruby multiple times

ruby,rspec

Aha, I think I found the solution! The trick appears to be allow_any_instance_of(Kernel).to receive(:gets).and_return 'yes' and calling that in a before block before the application code is pulled in - like so: describe 'ask' do before do stub(:puts).with('anything') stub(:puts).with('Please answer "yes" or "no".') stub(:gets).and_return 'yes' allow_any_instance_of(Kernel).to receive(:gets).and_return 'yes' require './lib/ask.rb'...

How can I stub a controller instance variable using RSpec?

ruby-on-rails-3,rspec,controller

In fact the instance variable is set to the value that you provide in the example, but that happens before the before_filter executes, so it ends up being set again. You could move the initialization from the before_filter into a method in the controller and stub that instead: before_filter {...

Problems installing RSpec

ruby-on-rails,rspec

Make sure, outside of the groups, you have gem "devise" the devise_for route helper is provided by the devise gem. And don't forget to run bundle install to install it in the project...

Rspec routing test not passing

ruby-on-rails,ruby,rspec

Try using a different syntax: expect(get: "/queue").to route_to( controller: "queue_videos", action: "show" ) ...

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

ruby-on-rails,rspec

worker = double allow(ResendWorker).to receive(:new).and_return(worker) expect(worker).to receive(:resend_message) instance.resend_if_failed ...

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

A should_receive expectation has to be set before you call the method under test; you're setting it afterwards. Since you need to set it before, you then have to make sure the object you've set up the expectation on ends up being operated on in the action. The normal way...

How can I stub a dependency in a Rails service

ruby-on-rails,rspec,vcr

foo = double(bars: 'whatever') allow(Foo).to receive(:new).with(:a_token).and_return foo or allow(Foo).to receive(:new).with(:a_token) .and_return double(bar: 'whatever') ...

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

ruby-on-rails,ruby-on-rails-4,rspec,rspec3

You don't need to add a custom validation. Consider using the numericality validation provided by ActiveRecord: class Student < ActiveRecord::Base validates :name, presence: true validates :roll, uniqueness: true validates :roll, numericality: { greater_than: 1, less_than: 80 } end Also write your test in this way: let(:student1) { Student.create(name: "sanjay", lastname:...

rspec test failing on expect(user.save).to be_true

ruby-on-rails,rspec

It appears that even though a unique email test was passing, requiring a unique user name was preventing a save. Using Factory Girl with username#{n} got my test to pass.

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

rspec,sidekiq

I think what you were looking for was and_yield: allow(Sidekiq::Queue).to receive_message_chain(:new, :any?).and_yield(<something>) Here's some sample code/specs for you (with values/method calls that I didn't know about stubbed out) that you can try yourself and change as you see fit: class SyncTest def already_syncing? Sidekiq::Queue.new(queue_name).any? { |q| q.args[0] == car_id }...

Rspec having difficulty testing #create with build controller method

ruby-on-rails,ruby,rspec

Sign in the user before calling the controller action. Please find the following: #testimonials_controller_spec.rb require 'rails_helper' describe TestimonialsController, type: :controller do let(:user) do FactoryGirl.create :user end before do sign_in user end describe "POST #create" do context "with VALID attributes" do it "creates new testimonial" do expect { post :create, testimonial:...

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

ruby-on-rails,ruby,rspec,mocking

I would rather try to assert the externally visible effects. Suppose you have a SomeGem.configuration method that you can use to retrieve the configured values, then you could write describe 'configuration block' do subject do lambda do SomeGem.configure do |config| config.username = "hello" config.password = "world" end end end it...

RSpec matcher that checks collection to include item that satisfies lambda

ruby,rspec,rspec-rails,rspec3

In RSpec 3, matchers are fully composable, which means you can pass any object which implements Ruby's === protocol (including a matcher!) to include and it will work properly. Lambdas in Ruby 1.9 implement the === protocol, which means you can do this: expect(changes).to include(lambda { |x| x.key == 'name'...

DRY code using Rspec matchers

ruby,rspec

You can store the arguments to be used more than once in an array, then splat (*) them into the argument list: css_args = ['selector', {text: 'text'}] expect(page).to(have_css(*css_args)) You can also pick your matcher with negate like so: expectation = negate ? :to_not : :to expect(page).send(expectation, have_css('selector', text: 'text')) ...

Not able to run rspec with Sequel

ruby-on-rails-4,rspec,sequel

I moved the code: RSpec.configure do |config| config.include RspecSequel::Matchers #...other config.. end from spec_helper.rb to rails_helper.rb It's working now....

controller is Nil in rspec test

ruby-on-rails,ruby,rspec

This is a request spec (which is basically a rails integration test) which is designed to span multiple requests, possibly across controllers. The controller variable is set by the request methods that integration testing provides (get, put, post etc.) If instead you use the capybara DSL (visit, click etc.) then...

Rspec: let does not work

ruby-on-rails,ruby,rspec

I see two mistakes: you havent wrapped your test within an it block (!) you try to associate events to order but order is not persisted Sidenote, the convention is now to use the following syntax: expect(order.events_paid?).to be true ...

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

ruby,rspec,tdd

I'm not sure what documentation you're working from, but it appears the open_datagram_socket requires a Module and cannot accept a Class as the third (handler) argument. Per the comment in http://www.rubydoc.info/github/eventmachine/eventmachine/EventMachine.open_datagram_socket, it appears this restriction may have been loosened in a later version of EventMachine...

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

ruby-on-rails-3,github,rspec,elasticsearch,circleci

The error message says circle.yml should be in the repo's root directory, but you have it the config directory.

Run block once before all capybara tests

ruby-on-rails,ruby,rspec,capybara

I think you are overengineering the task. Since you are to run it once, just run it: cb = lambda { puts 'I am run once' } RSpec.configure do |config| cb.call end ...

Faking instance variable in RSpec and Capybara feature spec

ruby-on-rails,ruby,rspec,capybara

There's no easy way to accomplish what you want. The feature spec is handled mostly by Capybara, not RSpec. Capybara runs the majority of the browser / rails server behavior in an external process. This make it inaccessible from RSpec's point-of-view. Thus you cannot use stubs / doubles in this...

How to stub Time.now.hour

ruby-on-rails,testing,time,rspec,stubbing

Another approach would be to use Timecop (or the new Rails replacement travel_to) to stub out your time for you. With Timecop you can have super readable specs with no need for manual stubbing: # spec setup Timecop.freeze(Time.now.beginning_of_day + 11.hours) do visit root_path do_other_stuff! end ...

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

ruby-on-rails,ruby,rspec

How about you write it like this? expect(subject.call(foo)) is not very pretty but it gets rid of the nesting. describe "#some_method" do subject { course.method(:some_method) } it 'returns the one after if given a project' do expect(subject.call(random[1])).to eq(random[2]) end it 'returns nil when it is the last' do expect(subject.call(random.last)).to be_nil...

NoMethodError undefined method sign_in rspec devise

ruby-on-rails,rspec,devise

You're not showing it, so I'm guessing that it's not there. You need to require "rails_helper" in your controller_spec.

How to continue a seeded RSpec run?

rspec

RSpec does not support a --continue flag. It would have to persist some state between runs about how far the last run got in the whole suite. It doesn't do this (and we have no plans to do so) but it would be pretty easy for someone to write an...

How to set text into Summernote textarea with Capybara + Poltergeist

rspec,capybara,poltergeist,summernote

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

Get environment variable from other proccess in Ruby

c#,ruby,rspec

Environment.SetEnvironmentVariable by default sets target to process. You should use User or Machine target: Environment.SetEnvironmentVariable("PORT", Convert.ToString(Fixture.Uri.Port), EnvironmentVariableTarget.User); MSDN documentation...

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

You should use mocks - https://www.relishapp.com/rspec/rspec-mocks/docs. user = double("user", id: 1, save: true) Then you should mock you method with double you've just created expect(User).to receive(:new).and_return(user) And then test redirect. expect(response).to redirect_to user_path(user) I hope this will help....

Using external variable in rspec-puppet test

ruby,rspec,puppet

You can do this by mocking Facter output. Something like: context 'service on debian' do let(:facts) { { :osfamily => 'Debian' } } it { should contain_service("ssh") } end context 'service on redhat' do let(:facts) { { :osfamily => 'RedHat' } } it { should contain_service("sshd") } end ...

Wait for Websocket Rails event to finish in test environment

ruby-on-rails,selenium,rspec,websocket,capybara

I solved this by writing a helper method that accepts a block of code. The helper method records the current time, then adds a function to the ajax start event that records the time that the ajax started in a sessionStorage variable. I can then run the code block passed...

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

ruby-on-rails,unit-testing,rspec,capybara

Libraries such as Machinist and FactoryGirl allow you to create entities using a template which has reasonable defaults, so that you only need to specify the properties that are relevant to the test. It's very common to use them in tests, as an alternative to fixtures.

array push pop in ruby

ruby,rspec

Those variables needs to be in initialize method: class RPNCalculator def initialize @arr=[] @ans=0 end def push(val) @arr.push(val) end def plus while @arr.size>=1 do @[email protected][email protected] end end def value return @ans end end Explanation: initialize is private by default and is called as obj.send(:initialize, *args, &block) in Class#new method's implementation....

Trouble in RSpec test - saving parent record twice

ruby-on-rails,ruby-on-rails-4,activerecord,rspec,nested-attributes

The issue is in sign_up_spec.rb. Your test has a let for user, which means the first time you mention user in your tests it will create a user. However, your application code is supposed to create the user itself. As I said in the comment, this is why in your...

Dynamic expectations in Rspec

ruby-on-rails,ruby,testing,rspec,tdd

You can use plain string interpolation: expect(current_path).to eq "/users/#{ User.last.id }" Or a route helper: expect(current_path).to eq user_path(User.last) ...

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

ruby-on-rails,ruby,rspec,watir,rspec-rails

Before you change $name to be "Xyz", or test for equality, you need to set $old_name to be equal to $name. Something like this: $name = generate_name self.name = $name $old_name = self.name $name = Xyz self.name = $name using expect($name).to_not eq($old_name) ...

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

ruby-on-rails,ruby,rspec,factory-girl

You can test the response status like this: expect(response.status).to eq(412) And the JSON response with: expect(response.body).to eq "{\"password_confirmation\":[\"doesn't match Password\",\"doesn't match Password\"],\"password\":[\"Password must contain 1 Uppercase alphabet 1 lowercase alphabet 1 digit and minimum 8 charecters\"]}" ...

How to create a Gemfile?

ruby,rspec

The Gemfile is just a text file within your project which contains a list of gems for use in your application. If you do not have one in your application, you can create the file using an editor of your choice, saving it as Gemfile (with no extension), and in...

Rspec testing find_or_create method

ruby-on-rails,rspec,mocking,simplecov

http://pastebin.com/kqJ39MBk Test should be looked like this one

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

ruby-on-rails,ruby,ruby-on-rails-3,rspec,actionmailer

It's not an rspec thing, it's an ActionMailer thing. Looking at: https://github.com/rails/rails/blob/master/actionmailer/lib/action_mailer/base.rb Take a look at the comments in lines 135-146: # = Sending mail # # Once a mailer action and template are defined, you can deliver your message or defer its creation and # delivery for later: #...

where to put config for turnip step definitions

ruby-on-rails,ruby,rspec

The RSpec.configure block mentioned in the turnip documentation can be found in spec/spec_helper.rb and/or spec/rails_helper.rb. It is possible that you have only one of the files. There, you can include your steps: RSpec.configure do |config| config.include MonsterSteps # other settings... end The difference between the two is that the former...

undefined method `before' for main:Object

ruby,rspec,serverspec

before should be implemented within describe: require 'spec_helper' describe "My Tests" do before(:all) do puts "ServerSpec tests on #{ENV['TARGET_HOST']}" end end Good luck!...

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

ruby-on-rails,ruby,rspec,devise

You can use the devise valid_password? method (more info here) In your spec: expect(user.valid_password?('password')).to be_truthy...

Rspec controller tests broken after switch to postgresql

ruby-on-rails,postgresql,rspec

It turns out the solution had to do with my database not properly cleaning itself, I ended up using the "Database_Cleaner" gem: https://github.com/DatabaseCleaner/database_cleaner

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

ruby-on-rails,rspec

So i figured it out with some help from a friend. This is the correct syntax with use of the rspec api documentation/dsl: require "spec_helper" require "rspec_api_documentation/dsl" resource "Data" do header "Accept", "application/json" header "Content-Type", "application/json" header "Host", "public.example.com" describe "Post a request to totals" do parameter :type,"selected data type"...

RSpec: execute the same expectation under different circumstances

rspec

You're testing two different cases - would suggest to separate them. describe 'statistics' do def have_statistics have_content('Statistics') end before { visit_statistics_page } it { expect(page).to_not have_statistics } it 'displays statistics when logged in' do login_as(create :user) expect(page).to have_statistics end end ...

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

ruby,rspec,mocking

For your workflow, I think it's going to work better to use a class_double than than to stub the Hashes class directly. allow(Hashes) is always going to require that the Hashes constant is defined. It's simply how Ruby works and RSpec can't do anything about that. With a class double,...

`allow_any_instance_of` mock not working in scope

ruby-on-rails,ruby,rspec

My bad. The original question was poorly written. Visiting the page is what makes the #quack call. The mocks must always be done before you do whatever it is that engages the method call. So this was my solution describe 'Ducks', type: :feature do before do ... end context 'is...

Rails test JS view from controller spec

javascript,ruby-on-rails,ruby-on-rails-4,rspec

By default, controller specs do not render views unless you specifically enable it: https://www.relishapp.com/rspec/rspec-rails/v/3-0/docs/controller-specs/render-views...

lazy evaluation and rspec's let method

ruby-on-rails,ruby,rspec

You're seeing invocations of the lazy comment method where there are none. However, comment will be lazy evaluated in the before block No, the before block you've show us has nothing to do with let(:comment). Using blog_post.comment is unrelated to Rspec, or let. It's using a method, comment, defined on...

RSpec Rails wont find my meta tags

ruby-on-rails,rspec,meta-tags

Assuming you are using Capybara, you can do what was described in this post: page.should have_css 'meta[name="description"]', :visible => false or page.find 'meta[name="description"]', :visible => false Capybara by default does not work on elements not directly visible to the user (title is visible at the top of the browser/tab, so...

Why spec does not see the class in the module?

ruby-on-rails,rspec

Because its namespaced, use DeviseModels::UserWithCustomEncryption.new

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

ruby-on-rails,ruby,rspec

If you want to test the output of your controller you need to use response.body not request.body. request.bodyis what is sent by the client when submitting a form.

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

jquery,ruby-on-rails,rspec,capybara,bootstrap

You can simply check which environment Rails is running: if Rails.env.production? javascript_include_tag "http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" else javascript_include_tag "/scripts/jquery/1.7.1/jquery.js" end There is most likly a plethora of gems for this though. Added: A nice eat the cake and keep it approach if you still want to use gems (like jquery-rails) and the sprockets...

Setting a session value through RSpec

ruby-on-rails,ruby,session,rspec

This will change based on the spec type. For example, a feature spec will not allow you to directly modify the session. However, a controller spec will. You will need to include the helper methods module into your example group. Say you have a WidgetsController: require 'support/spec_test_helper' RSpec.describe WidgetsController, type:...

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

ruby-on-rails,ruby-on-rails-4,rspec,factory-girl

For my use case, this worked: 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 {Owner.new} end end This pattern simply assigns a new, unused owner object to the Kid factory (to pass validations). Since Parent...

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

ruby-on-rails,angularjs,rspec,capybara

My guess is that your create(:fighter) call is running in a different thread (and database transaction) than the AJAX get request. Try adding this snippet to your rails_helper. class ActiveRecord::Base mattr_accessor :shared_connection @@shared_connection = nil def self.connection @@shared_connection || retrieve_connection end end ActiveRecord::Base.shared_connection = ActiveRecord::Base.connection Source: https://github.com/jnicklas/capybara#transactions-and-database-setup...

Testing my rake task - Rails 4

ruby-on-rails,ruby,ruby-on-rails-4,rspec

You're not "losing" your instance variable. Your instance variable is a query which will yield different results before and after your rake task. Your modified test executes the query before the rake task and saves something derived from the result in a local variable (i.e. the id of the first...

Rspec view test with url parameters

ruby-on-rails,unit-testing,testing,rspec,rspec-rails

Because these are redirects, controller testing with render_views will not work. Nope, you are just doing it wrong. If StaticpagesController#dashboard accepts url parameters you should test how it responds to said parameters in the controller spec for StaticpagesController. RSpec.describe StaticpagesController, type: :controller do describe 'GET #dashboard' do render_views it...

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 think you using invalid validation helper i.e. validate instead of validates.

Rails 4: Factory Girl & Rspec with associated Model

ruby-on-rails,ruby,rspec,tdd,factory-girl

Add the uploadedzip_id to the posted params: before(:each) do post :create, campaign: attributes_for(:campaign), uploadedzip_id: 123456 end ...

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

ruby-on-rails,ruby,rspec

Just test that the book.entries association is empty: expect(book.entries).to be_empty As book is a local variable in your test, you will not get a false negative result if you keep your test atomic. Some best practices on rspec....

How to remove entries using a model function?

ruby-on-rails,rspec

You're right that the remove_entry method should be in AddressBook since it is modifying the address book's entries collection (and the Entry class should know nothing about AddressBook or its internals). However, because your add_entry method doesn't expose the Entry class you'll want to make remove_entry work the same way,...

Replace fixtures with factory girl in for generated scffold test cases

ruby-on-rails,rspec,factory-girl

FactoryGirl.build doesn't persist to the database, you need FactoryGirl.create.

Can I alias a nested RSpec matcher?

ruby,rspec,rspec3,rspec-expectations

Sure you can do that. Make it a helper method. Helper Methods These are just normal Ruby methods. You can define them in any example group. These helper methods are exposed to examples in the group in which they are defined and groups nested within that group, but not parent...

Testing Rails app with RSpec and Capybara

ruby-on-rails,rspec,capybara

You could test with Capybara, so long as you use a driver that supports javascript, such as Selenium or Poltergeist - see https://github.com/jnicklas/capybara#drivers However, although I'm not an AngularJS user, I do know that it's designed to be testable, and I imagine you'd be much better off using a tool...

How to configure RSPEC to never run on RAILS_ENV production

ruby-on-rails,ruby,rspec

In your spec_helper.rb, before any RAILS_ENV assignment: raise "Not in test" unless ENV['RAILS_ENV'] == "test" ...

Logging for rspec selenium/capybara tests running in Browserstack

ruby,selenium,rspec,capybara,browserstack

The bits of advice I can give you is: 1:. Each test should be a single use case scenario. If it fails you know why 2:. If you need to perform many steps to achieve a use case scenario then you should be abstracting your elements into classes that represent...

Using validate_presence_of with strict validations

ruby-on-rails,ruby,rspec,shoulda

I think strict validators are tested like this: describe Thing do subject(:thing) { FactoryGirl.build_stubbed :thing } it { should validate_presence_of(:status).strict } end ...

How to disable a before_action in a controller spec?

ruby-on-rails,ruby-on-rails-4,rspec,rspec-rails

When doing controller specs and faking login I like to use an expectation to stub out authorisation instead. i.e. in your situation: require "rails_helper.rb" describe MaterialsController do before :each do allow(controller).to receive(:require_authorisation_to_view_materials).and_return(true) end #..snip end Or even better require "rails_helper.rb" describe MaterialsController do before :each do allow(controller).to receive(:current_user).and_return(FactoryGirl.create(:admin_user) end #..snip...

RSpec controller test error: controller does not implement method

ruby-on-rails,ruby-on-rails-4,rspec,devise

You're stubbing create_stripe_customer as a class method, but it's actually an instance method.

Where is the webkit_debug log located?

ruby-on-rails,rspec,capybara-webkit

By default, capybara-webkit prints directly to standard error. More specifically: The driver consists of two components: a Ruby adapter which conforms to the Capybara API, and a server process (written in C++) which implements a fake WebKit browser. When logging is enabled, the C++ process prints entries to stderr using...

How to diagnose slow rails / rake / rspec tasks

ruby-on-rails,ruby,rspec,rake,rakefile

Thanks to @MaxWilliams for the link to this post How do I debug a slow rails app boot time? I started using Mark Ellul's Bumbler - http://github.com/mark-ellul/Bumbler It gave me exactly what I wanted - an insight into what's going in the background and which gems are taking the time....

Passing Two Parameters on a JSON POST Request in Rspec

ruby-on-rails,ruby,json,post,rspec

I think you should send a single hash in your post. Try the following: post :create, json.merge!(access_token: @api_app.access_token) ...

Rspec test public controller method passing params to private controller method

ruby-on-rails,ruby-on-rails-4,rspec,controller,rspec-rails

Stubbed methods return nil by default. Use and_return to specify the value returned by the stub:: StripeService.should_receive(:new).and_return(whatever) or using the newer syntax expect(StripeService).to receive(:new).and_return(whatever) EDIT Pardon my hand-waving. Your stub must return an object that will act like an instance of StripeService to the extent required for the purposes of...

RSpec 3 - Test controller action that does not have routes

ruby-on-rails,ruby-on-rails-4,rspec,controller,rspec3

action_b should really be a private method. Normally, you would not test this directly, you would verify it implicitly by testing action_a.

Specific test behaviour for ruby gem — mocking sleep

ruby,rspec,gem

As you say it is difficult to know whether you are actually in a test-like environment, so the solution is not to try: provide a method that allows users of your gem to indicate that sleeps should not occur. You could try and autodetect whether you should default to not...

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

rspec

I addressed this need by writing my own RSpec formatter. Put the following class in spec/support, make sure it's required, and run rspec like so: rspec --format SpecTimeFormatter --out spec-times.txt class SpecTimeFormatter < RSpec::Core::Formatters::BaseFormatter RSpec::Core::Formatters.register self, :example_started, :stop def initialize(output) @output = output @times = [] end def example_started(notification) current_spec...

Capybara - Determine if selector count has changed

ruby,rspec,capybara

previous_count = page.all('input').size click_on("Hide") new_count = page.all('input').size expect(new_count).to_not eq(previous_count) or expect do click_on("Hide") end.to change { page.all('input').size } ...

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

ruby-on-rails,rspec

I found the answer. I needed to pass human_attribute_name of the attribute into the translation as a parameter attribute. The test now passes like this: it "is invalid with special characters" do account = FactoryGirl.build(:account, name: "test_account_*namre") account.valid? expect(account.errors[:name]).to include(I18n.t('activerecord.errors.models.account.attributes.name.invalid', attribute: Account.human_attribute_name(:name))) end ...

model's class trying to access database even using double

ruby-on-rails,ruby-on-rails-4,rspec,rspec-rails

Your classes are trying to connect to the database as soon as they are defined - the mere act of requiring that base class will attempt a database connection, because the class definition contains the call to establish_connection You could skip the call to establish_connection when in tests - if...

Testing tools available for Rails application [closed]

ruby-on-rails,ruby,rspec

Definitely read the Rails guides on testing best practices; there's a ton of books, blog posts, and Youtube videos out there on how to test. But part of your question has been a particular pain point for me so I'll give a brief answer here too: Which of these complex...

Testing destroy method failure in Controller test

ruby-on-rails,rspec

How are you setting @item in the spec? I suspect it's not actually being stubbed. Update: Without seeing your controller, I can't give the exact code, but normally it would be something like this: item = double allow(Item).to receive(:find).and_return(item) allow(item).to receive(:destroy).and_return(false) Update 2: Expanding out, you set item with: current_user.collections.find(params[:collection_id]).items.find_by_id(params[:id])...

rails after_create not updating parent model

ruby-on-rails,ruby,rspec

In after_create callback it's not guaranteed that you will have an id of record. Use after_commit on: create instead.