Rspec How to specify expected return values?

I'm new to RSpec and as I was writing a spec test I came across a problem where the spec tests are passing even though the return values are different than what I specified in my expectations. For example: @q= Query.new @q.should_receive(:number_to_name).with(0).and_return("no such boro") @q.number_to_name(0) This passes even though the Query.number_to_name is returning a different value when I call it with 0. I don't understand what to make of this.

Rspec Rails spec testing with multiple projects

So I'm looking to test two projects that I have: API that serves as the back end. Public facing platform. The #2 project makes calls to #1 in order to create/read/update/delete records. I've heard rumors that rspec testing with two parallel projects is not possible, but I'm interested in at least looking at a few discussions about it. My google fu may just not be that great today and all I can find are resources for speeding up rspec tests. Is this possible or will I need to locate some s

Watir Rspec Table Cell

Now I have the problem that I can identify the text in a table. For this Site I choose from Paperback weiß 90g 12 cm x 19 cm number of pages: 24 Click "Cover berechnen" Test with test::unit okay assert(@browser.th(:text => "Buchrückenbreite").exists?) assert(@browser.td(:text => "0.13 cm").exists?) Test with rspec incorrect @browser.th(:text => "Buchrückenbreite").should == true @browser.td(:text => "0.13 cm").should == true Error Message: expected: true got: #<W

Custom screeshot for watir-rspec reporter

I am migrating from watir-webdriver with rspec to watir-rspec (not a big change). But now I want to make use of the reporter to link the screenshots I take with the screenshot gem. I am struggling on how to to this and I don't want to use the standards screenshots because I have another helper function that does some work on the image and the screenshot gem allows me to get screenshots of specific elements. On the watir-rspec documentation it claims we just have to add this three lines, but I a

Why is it a code smell to use any_instance_of in Rspec?

There aren't many resources online for this but the closest to the answer is on the relishapp.com website: The rspec-mocks API is designed for individual object instances, but this feature operates on entire classes of objects. As a result there are some semantically confusing edge cases. For example, in expect_any_instance_of(Widget).to receive(:name).twice it isn't clear whether a specific instance is expected to receive name twice, or if two receives total are expected. (It's th

Rspec Rails 5 - Factory Girl callbacks with attributes_for

I'm with the following problem. How can I use the attributes_for of the Factory Girl to call a callback after it? My code: FactoryGirl.define do factory :transacao_transferencia_hierarquia, class: Transacao do tipo { 'transferencia' } valor { '250' } conta_origem_id { nil } conta_destino_id { nil } trait :igual do conta_origem_id { nil } conta_destino_id { nil } after(:build) do |transacao_transferencia_hierarquia| conta_origem_hierarquia_igual

Rails 5 + Rspec + API Testcase inside MODEL or Request

Rails 5 + Rspec + API Testcase inside MODEL or Request Code: require "rails_helper" RSpec.describe "req", :type => :request do it "creates a api request page" do headers = { 'Content-Type' => 'application/json', 'Authorization' => 'Basic bW9oZC5hbmFzQG6bW9oZGFuYXNAMTIz', 'Token' => "222222222222222222" } get "/api/product/list", {}, headers expect(response.status).to eq(200) end end I am getting Unauthorised error message and token I passed i

RSpec console log returns 302, but test log shows 401

I have a simple test written to check that users can't post into a controller with before_action :authenticate_user!. The test reads: context 'when the user is not logged in' do it 'returns 401' do sign_out user post wikis_path(params: wiki) expect(response).to have_http_status(401) end end The output in the console is: Failure/Error: expect(response).to have_http_status(401) expected the response to have status code 401 but it was 302 But when I check the test log

Rspec Page has field both visible and invisible at the same time

How is it possible the following spec (RSpec 3.8 + Capybara 3.8.2) passes? scenario 'he can dismiss it', js: true do find(:dataAttribute, 'tags.addButton').click expect(page).to have_field('tag[name]', visible: false) expect(page).to have_field('tag[name]') end Here the HTML <input class="input" type="text" name="tag[name]" id="tag_name" />

rspec's should_receive on a non-mock object?

Is it possible to call should_receive on a non-mock object? If it is, I'm wondering why this test doesn't pass. SiteStyle has_many images and when I call duplicate! on a site_style, I want the images to call duplicate on themselves as well. The test fails. The actual images get duplicated though. Why is that? SiteStyle model: class SiteStyle < ActiveRecord::Base belongs_to :site belongs_to :user validates_presence_of :name, :user has_many :images, :as => :imageable, :order =>

Stub, Should_Receive, and Before Blocks in RSpec Functional Tests

The code samples below show a refactor from the chapter on controller specs in The RSpec Book: require 'spec_helper' describe MessagesController do describe "POST create" do it "creates a new message" do message = mock_model(Message).as_null_object Message.should_receive(:new). with("text" => "a quick brown fox"). and_return(message) post :create, :message => { "text" => "a quick brown fox" } end it "saves the message" do message

Rspec Ruby on Rails tutorial chapter 8.2.6 Capybara element not found error + no method error undefined method it

I was working through the tutorial and got this error Failures: 1) Authentication signin followed by signout Failure/Error: before { click_link "Sign out" } Capybara::ElementNotFound: no link with title, id or text 'Sign out' found # (eval):2:in `click_link' # ./spec/requests/authentication_pages_spec.rb:48:in `block (4 levels) in <top (required)>' I have thoroughly researched this question and although there are similar questions, I have tried their soluti

Why is Zeus running slower than RSpec?

Some of the individual tests are lightning fast with Zeus, and others are pretty dang slow. If I do: time rspec spec/ The result is: Finished in 35.36 seconds 220 examples, 0 failures real 0m59.018s user 0m43.723s sys 0m2.495s But if I use Zeus: time zeus rspec spec/ The result is: Finished in 7 minutes 9 seconds 220 examples, 0 failures real 7m13.053s user 0m0.279s sys 0m0.047s Notice the "user" and "sys" times in both, those line up with what I would expect. However, t

Rspec Asserting height has changed using Capybara

I have an iframe which is the target of a form: <form target="preview"> <textarea name="content"></textarea> </form> <iframe name="preview"></iframe> The form is submitted when the user types in the textarea (I've left out the debouncing code for brevity): $('textarea').keyup(function() { // debouncer ensures this happens at *most* every two seconds $('form').submit(); }); And I have a script which keeps the iframe's height adjusted to its conte

Rspec Capybara have_selector is not working

On my view I have a checkbox <input type="checkbox" id="modal-checkbox" class="painter-modal-checkbox" data-reactid=".1.1:1.0.0"> On my capybara code I am trying to use the have_selector method expect(page).to have_selector("#modal-checkbox") This fails, when I am tracing the page with print page.html I can confirm that my html code is there, why does this test fails.

Rspec How to test the parameters of a long chaining method without create tons of doubles

I have an Active Record query like so: user.templates.where(id: @template_id).joins(:another_record).pluck('templates.id').uniq But I just want to test that the where is getting called with the correct id. Is there a way to do this without having to create several doubles that just respond to the remaining methods. Essentially I want something like expect_any_instance_of(User).to receive_message_chain('templates.where').with(id: target_id).and_return(a_double_that_returns_another_double_tha

Rspec Capybara/Poltergeist and Braintree testing

I am running into errors testing my Braintree sandbox payments using Rspec, Capybara, and Poltergeist in a feature test. I have it set up to do exactly what a human would do in development (entering payment info and clicking submit). It works fine in development. However, when I run my spec, I get a javascript error on the payment page when it loads: Capybara::Poltergeist::JavascriptError: One or more errors were raised in the Javascript code on the page. If you don't care about these error

Rspec Can I automatically add shared examples to certain tests?

I would like to run a shared example automatically if the described_class matches some description. For example, when I have a module I often write a shared example and include it into anything which includes the module. module ExtraStuff def self.stuff 42 end end class Thing include ExtraStuff end shared_examples ExtraStuff do it 'has stuff' do expect( described_class.stuff ).to eq 42 end end describe Thing do it_behaves_like ExtraStuff end But sometimes I forget. Or

Efficiently using Rspec/Capybara to fill out each phase of a form

I'm using rspec and capybara to do some testing for some form-paths we have, but it's developed in PHP, so just looking for HTML. So in order to get to the next question of the process, I have to answer the previous one question form and click_button to get to the next part. I'm doing this for each. Here's an example of what I'm dealing with: describe 'Fourth Step' do before do visit '/thiseffingwebsite' select 'someAnswer', from: 'someQuestion' click_button "Continue" sele

Rspec Model with "method missing" behaves differently in Rails 4 than Rails 3 (can cause 'stack level too deep' error)

I have a Rails application that was working fine with Rails 3.2.14. I have just started to work on upgrading it to Rails 4, essentially following along with Railscast episode 415. I got as far as the part where I try to run my rspec tests to find many now fail with the following error: Failure/Error: Unable to find matching line from backtrace SystemStackError: stack level too deep I also checked my Cucumber tests and find similar failures. stack level too deep (SystemStackError) As

Rspec phpspec - assert that object has changed during method call

if i have the following method: function changeObject($object) { $object = new \stdClass(); } This is a very silly example, but it is used to illustrate my question. The object that is passed may be changed during the method call, but the method does not return the object. using phpspec how can I assert that the object was modified?

Rspec How to set Poltergeist timeout option with Capybara when running against an app_host?

According to Poltergeist docs, to init Poltergeist with options: options = { timeout:0 } Capybara.register_driver :poltergeist do |app| Capybara::Poltergeist::Driver.new(app, options) end So, I don't have an app to pass to the Poltergeist init. How to set it up without an app? The following did not set the option: options = { timeout:0 } Capybara.register_driver :poltergeist do Capybara::Poltergeist::Driver.new( options ) end

Running phantomjs with external libraries in Rspec

I'm trying to run a set of feature specs in PhantomJS using Poltergeist and Rspec. The specs pass normally, but when I switch jQuery to a CDN they fail. Is there a way to get PhantomJS to load external JavaScript libraries? Failure/Error: visit root_path Capybara::Poltergeist::JavascriptError: One or more errors were raised in the Javascript code on the page. If you don't care about these errors, you can ignore them by setting js_errors: false in your Poltergeist configuration (see

How to properly test the Mail object in rspec

In my reading of rspec, it sounds like doing something like... expect_any_instance_of(Mail).to receive(:deliver) ...should cause rspec to replace the deliver method with it's own so that the deliver method isn't actually called. But in my case when I do that I get the following error in my test which leads me to believe that it is still being called. Failure/Error: task.send_email_alert('test', dummy) Errno::ECONNREFUSED: Connection refused - connect(2) for "localhost" port 2

How to disable Hiera debug output in rspec-puppet test

I have the following spec file require 'spec_helper' describe 'PLC', :type => 'class' do let(:hiera_config) { 'spec/fixtures/hiera/hiera.yaml' } hiera = Hiera.new({ :config => 'spec/fixtures/hiera/hiera.yaml' }) abc = hiera.lookup('PLC::PLC_LINE',nil,nil) let(:hiera_data) {{ :PLC_LINE => abc }} it{ should contain_file('/test/rspec/etc/PLC').with( 'ensure' => 'file', 'owner' => 'root', 'group' => 'root', 'mode' =>

Rspec How to test field visibility with Capybara?

Note: This question is about using Capybara 1.1.2, not current versions. I have a hidden text field, and a button which make it visible. hidden text field: <input type="text" name="Franchise Name" id="new_franchise_name" placeholder="Franchise Name" style="display:none;" /> button and js event handler which makes the the above field visible: <button class="btn btn-medium" id="create_franchise" data-remote="true" >Create New Franchise</button> $('#create_franchise').clic

Rspec Disabled checkbox with Capybara

How can I verify with Capybara that a checkbox is disabled? I have tried few options but nothing seems to work. Last attempt was expect(page).to have_field("input[type='checkbox'][value='agreement']", disabled: true) As always, Thanks.

RSpec: in-depth differences between before(:all) and before(:each)

Ok, so I've ran into a very strange issue, directly connected with before blocks. I'm doing a integration testing via Watir and RSpec. For a simple test to check if user can perform a login I'm creating a 'user' record in the db by means of factory_girl. So I put the following code: before(:each) do @user = Factory(:user) end if "should perform a login" do # do stuff end In do stuff I call a browser and see how the user tries to login. Unfortunately, somehow he cannot do that — "Userna

Rspec Why the cucumber features keeps running even though it fails?

Its a rails 2.3.5 app. I'm using the rspec and cucumber for testing. When I run autospec, it runs correctly with the warning (Not running features. To run features in autotest, set AUTOFEATURE=true.) as below: [~/rails_apps/automation (campaign)⚡] ➔ autospec (Not running features. To run features in autotest, set AUTOFEATURE=true.) (Not running features. To run features in autotest, set AUTOFEATURE=true.) loading autotest/rails_rspec /home/millisami/.rvm/rubies/ree-1.8.7-2010.01/lib/ruby/1.

What is the right method to call Rspec.configure when spork is used? prefork or each_run?

I need to setup mongoid collections clean up for each spec. What is the right method to call Rspec.configure when spork is used? prefork or each_run? Here is my current setup: require 'rubygems' require 'spork' Spork.prefork do # Loading more in this block will cause your tests to run faster. However, # if you change any configuration or code from libraries loaded here, you'll # need to restart spork for it take effect. require File.dirname(__FILE__) + '/../config/environment.rb' re

How to test headers with rspec and rack-test in Sinatra

So I have a Sinatra app that receives an XML via a HTTP POST from another service. I want to test it locally. I have a test XML-file that I send to the endpoint. That goes well. I also set some headers like this: post '/', xml, 'HTTP_X_MY_AWESOME_HEADER' => "It's value" where xml is the exact copy of normal XML that is being sent to my endpoint. But the header I pass as a parameter is never displayed in output. Am I doing something wrong here? There are a lot of posts around here about it

Rspec Getting "undefined method `env' for nil:NilClass" in integration test for OmniAuth

I have Omniauth test mode on: spec_helper (I put it at the bottom of the file, right before end): #Turn on "test mode" for OmniAuth OmniAuth.config.test_mode = true and this is my test: spec/request/authorization_pages_spec.rb: describe "signin" do before { visit signin_path } . . . describe "with OmniAuth" do before do OmniAuth.config.add_mock :facebook, uid: "fb-12345", info: { name: "Bob Smith" } visit root_path end describe "Face

Rspec Why won't Capybara select the right item in a select menu?

When you save_and_open_page, you can see that my form contains: <label class="select optional control-label" for="assignment_role_id">Role</label> <select class="select optional" id="assignment_role_id" name="assignment[role_id]"> <option value="819">admin</option> <option value="820">customer</option> </select> Why, then, won't Capybara select the right item in the drop down menu? I get: Failure/Error: select("customer", :from =>

Rspec expect raise_error ObjectDisabledException throws NameError exception

I have been using the watirspec-master files as examples to write my own RSpec tests. I recently encountered a situation in which I need to test for an exception thrown by a click or set event. I wrote the following test based on code in the checkbox_spec.rb file. I just changed the original from the lambda syntax to expect syntax. el4 = browser.checkbox(:id, "category_8") expect { el4.set }.to raise_error(ObjectDisabledException) When executed, this code complains about an uninitialized cons

Rspec testing for devise helper - devise_error_messages

I have the following helper: def devise_error_messages! return "" if resource.errors.empty? messages = resource.errors.full_messages.map { |msg| content_tag(:li, msg) }.join sentence = I18n.t("errors.messages.not_saved", :count => resource.errors.count, :resource => resource.class.model_name.human.downcase) html = <<-HTML <div id="error_explanation" class="alert alert-danger"> <h2>#{sentence}</h2&

Rspec double expect/allow anything

I have a test double that I'd like to be able to receive any message. I know I can expect the double to receive a certain message and return a value like so: foo = double() allow(foo).to receive(:bar) { "Foobar" } I can also allow foo to receive any message using #as_null_object like: foo = double() foo.as_null_object Is there any other syntax for this? Seems I should be able to do something like: allow(foo).to receive(:anything)

Rspec Using SitePrism's page object elements to perform page assertions

I want to know if there's a way to perform a page.should assertion with a page object element directly, instead of giving the xpath or CSS selector string as a parameter. i.e.: Page class: class FooClass < SitePrism::Page element :action_select, '.autocomplete.medium' end Step definition: page.should have_css('.autocomplete.medium') #Sort of thing desired: page.should have_css(action_select.get_css) That .get_css does not exist but it's used to illustrate what's desired.

Rspec Integration testing with Capybara

I'm trying to do a integration test of my app to get covered all the funcionalities. My app just uploads a file and it leads you to another page with a message 'Your database has been updated¡¡'. The user can't see it but when he uploads the excel file it updates the database. Well, I've used Capybara with Rspec to be able to test that I upload an excel file. The test pass to green but I don't understand why, cause I've written a false message to check that the test works propperly and still pas

Convert RSpec 2 "to have().errors_on" matcher to RSpec 3

In my Gemfile gem 'rspec-rails', '~> 3.3' I figured out, that the errors_on matcher moved to another gem: https://github.com/rspec/rspec-collection_matchers I'm positive that there must a way to achieve the same within RSpec 3. How can I convert the RSpec 2 have().errors_on matcher to RSpec 3? expect { click_button(I18n.t('helpers.submit.accounting.update')) }.to have(4).errors_on(:share_ksk, :central_office, :limit_value, :fix_disagio) I tried: expect { click_button(I1

rspec request test sign in without Devise

I'd like to log in a user in my request test, but couldn't get it work. I'm not using Device. Here's my code spec/support/spec_test_helper.rb module SpecTestHelper def log_user_in(user) post login_path, params: {session: {email: user.email, password: 'password'}} end end spec/requests/like_a_table_spec.rb require 'rails_helper' RSpec.describe 'LikeATable', type: :request do it 'will put table in wish list' do log_user_in(create(:user))

Rspec Many rpsec tests with test_sign_in fail after upgrading to Rails 3.1, maybe a cookie problem?

I have upgraded to Rails 3.1 and everything seems to work fine. But the tests (RSpec) fail anyhow, e.g. the following one: describe "for admin user" do before(:each) do @city = Factory(:city) @user = Factory(:user) @business = Factory(:business, :user_id => @user.id, :city_id => @city.id) @admin = test_sign_in(Factory(:user, :email => "admin@example.it", :admin => true)) end it "should have an edit l

Rspec Check a route does not exists in Rails 4

I deactivated the user registration (Gem Devise) and I want to make a test to be sure the route /users/sign_up does not exists. To do this I created a test in spec/features/user_spec.rb require 'spec_helper' require 'capybara/rspec' feature "Users" do scenario "could not register " do expect(:get => "/users/sign_up").not_to be_routable end end When I run this test, I have this error : 1) Users could not register Failure/Error: expect(:get => "/users/sign_up").not_to be_rou

Rspec flagging many errors in gems

I am trying to set up Rspec for the first time. I have deleted all the old generated specs from spec/models and spec/controllers Gemfile group :development, :test do gem 'jasmine-rails' gem "jasmine-core", "~> 1.3" gem 'binding_of_caller' gem 'rspec-rails', '~> 3.0.0' gem 'factory_girl_rails' end group :test do gem "faker", "~> 1.1.2" gem "capybara" gem "database_cleaner", "~> 1.0.1" gem "launchy", "~> 2.3.0" gem "selenium-webdriver", "~> 2.39.0" gem "

Rspec Unable to click bootstrap modal dialog buttons using Poltergeist

When I click on a button, a bootstrap modal popup displays. I tried to click on the OK or cancel button using Poltergeist functions as below, but none worked. Either the functions doesn't work or clicks outside. <div class="modal-footer"> <a class="btn cancel" data-dismiss="modal" href="#">Cancel</a> <a class="btn proceed btn-primary" href="#">OK</a> </div> click_link "Release" page.driver.render('ReleaseOKCANCEL.jpg', :full =>true) On Clicking 'release

How do I use Rspec and Capybara to verify that I have no dead links?

I'm trying to use Rspec and Capybara to verify that generated HTML pages have no dead links. Most (if not all) of the links are to relative HTML pages on the same file system. What I'm looking for is something like: it 'has no broken links' do all('a') do |link| visit link[:href] # 200 is the Ok HTTP response page.status.should == 200 end end However, this is not generating any syntax errors, but nor is it finding links that actually are broken. I suspect there's something wr

rspec check array elements for instances of numbers

How to check if the elements of arrays are containing only numbers (integers)? describe "#draw" do it "returns an array" do expect(@lottery_tip.draw).to be_a_kind_of Array end it "has six elements" do expect(@lottery_tip.draw.count).to eq(6) end it "s elements are only numbers" do expect(@lottery_tip.draw).to ??? end end My simple LotteryTip Class works but i'm wondering how to check the type of the elements in that returning array...

  1    2   3   4   5   6  ... 下一页 共 6 页