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...
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...
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...
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 ...
ruby-on-rails-3,testing,rspec,controller
Try: expect(session['dr']).to eq("dr"). session values are separate from assigns....
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') } ...
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...
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....
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...
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...
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...
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'...
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 {...
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...
Try using a different syntax: expect(get: "/queue").to route_to( controller: "queue_videos", action: "show" ) ...
worker = double allow(ResendWorker).to receive(:new).and_return(worker) expect(worker).to receive(:resend_message) instance.resend_if_failed ...
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...
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') ...
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:...
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.
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 }...
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:...
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...
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'...
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')) ...
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....
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...
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 ...
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...
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.
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 ...
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...
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 ...
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...
You're not showing it, so I'm guessing that it's not there. You need to require "rails_helper" in your controller_spec.
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...
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...
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...
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....
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 ...
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...
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.
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....
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...
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) ...
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) ...
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\"]}" ...
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...
ruby-on-rails,rspec,mocking,simplecov
http://pastebin.com/kqJ39MBk Test should be looked like this one
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: #...
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...
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!...
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...
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
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"...
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 ...
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,...
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...
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...
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...
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...
Because its namespaced, use DeviseModels::UserWithCustomEncryption.new
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.
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...
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:...
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...
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...
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...
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...
ruby-on-rails,regex,rspec,shoulda
I think you using invalid validation helper i.e. validate instead of validates.
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 ...
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....
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,...
ruby-on-rails,rspec,factory-girl
FactoryGirl.build doesn't persist to the database, you need FactoryGirl.create.
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...
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...
In your spec_helper.rb, before any RAILS_ENV assignment: raise "Not in test" unless ENV['RAILS_ENV'] == "test" ...
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...
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 ...
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...
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.
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...
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....
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) ...
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...
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.
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...
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...
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 } ...
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 ...
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...
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...
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])...
In after_create callback it's not guaranteed that you will have an id of record. Use after_commit on: create instead.