Rspec model validation - ruby-on-rails-3

i try to use TDD Rspec for model validation in rails 3.
my user_spec.rb file look like
require 'spec_helper'
describe User do
before { #user = User.new(name: "eric", country: "hawaii", email: "nice#nice.ch", password: "nicenice") }
subject { #user }
it { should respond_to(:name) }
it { should respond_to(:email) }
it { should be_valid }
end
after running rspec spec/models/user_spec.rb, i get an error message
No DRb server is running. Running in local process instead ...
..F
Failures:
1) User
Failure/Error: it { should be_valid }
TypeError:
type mismatch: String given
# ./spec/models/user_spec.rb:37:in `block (2 levels) in <top (required)>'
Finished in 0.09495 seconds
3 examples, 1 failure
Failed examples:
rspec ./spec/models/user_spec.rb:37 # User
Randomized with seed 42015
should be_valid expected a string?

Related

NoMethodError running Integration Test, RailsTutorial Ch9

I'm having an issue where my integration tests do not seem to find the log_in_as method from my test_helper.rb
I have been following Michael Hart's Rails tutorial, so I was hoping not to massively refactor my code to try and get this to work. I would like to continue on through the book without having to exclude the tests, since it is pretty test heavy afterall.
Error:
UsersLoginTest#test_login_with_remembering:
NoMethodError: undefined method `log_in_as' for #<UsersLoginTest:0x00000005b18460>
test/integration/users_login_test.rb:43:in `block in <class:UsersLoginTest>'
User_login_test.rb:
require 'test_helper.rb'
class UsersLoginTest < ActionDispatch::IntegrationTest
.
.
.
test "login with remembering" do
log_in_as(#user, remember_me: '1')
assert_not_empty cookies['remember_token']
end
test "login without remembering" do
# Log in to set the cookie.
log_in_as(#user, remember_me: '1')
# Log in again and verify that the cookie is deleted.
log_in_as(#user, remember_me: '0')
assert_empty cookies['remember_token']
end
end
test_helper.rb:
ENV['RAILS_ENV'] ||= 'test'
class ActiveSupport::TestCase
fixtures :all
# Returns true if a test user is logged in.
def is_logged_in?
!session[:user_id].nil?
end
# Log in as a particular user.
def log_in_as(user)
session[:user_id] = user.id
end
end
class ActionDispatch::IntegrationTest
# Log in as a particular user.
def log_in_as(user, password: 'password', remember_me: '1')
post login_path, params: { session: { email: user.email,
password: password,
remember_me: remember_me } }
end
end
I had this same issue. There are two problems I had to fix:
Make sure there is only one test_helper.rb file, and
test_helper.rb is in the right folder
Hope this helps!

Record is not updating in rails

This is my first rails application. My task is to display, delete and update the records using .ajax(). I have displayed and deleted the records but i cant update the records i couldn't figure out what is going wrong. My controller code is
def update
#aj = Aj.find params[:id]
respond_to do |format|
if #aj.update(aj_params)
format.html { redirect_to #aj, notice: 'Aj was successfully updated.' }
format.json { render :show, status: :ok }
else
format.html { render :edit }
format.json { render json: #aj.errors, status: :unprocessable_entity }
end
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_aj
#aj = Aj.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def aj_params
params.require(:aj).permit(:name, :title, :content)
end
end
and my route file is
match '/ajs/' => 'ajs#update', :via => :patch
match '/ajs/:id/edit' => 'ajs#edit', :via => :get
and could able to edit my form after changing the data when i click on update button it given the error
Couldn't find Aj without an ID
# Use callbacks to share common setup or constraints between actions.
def set_aj
#aj = Aj.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
edited:
I have javascript code in html itself
$(document).on("click", ".edit", function(){
var id = $(this).data('id');
alert("edit"+id)
$.ajax({
url: "ajs/"+id+"/edit",
type: "get",
data: id,
//dataType: "html",
success: function(data) {
$("#mybox").html(data);
$(document).on("click", "#subid", function(){
alert(id);
$.ajax({
url: "ajs/"+id,
type: "patch",
success: function(data) {
alert("success");
},
error: function(){
alert("error")
}
}); // show ajax() closed
});//show click() closed
},
error: function(){
alert("error")
}
}); // show ajax() closed
});//show click() closed
I have added a id for the update button and id name is "subid " when i click on that button i am passing my id am getting id of the row. when i used ajax for passing that id now i am getting another error:
No route matches [PATCH] "/ajs"
Rails.root: /home/liplw015/Documents/rails/ajaxjs
In my console:
Started PATCH "/ajs/134" for 127.0.0.1 at 2014-07-14 09:38:09 +0530
Processing by AjsController#update as */*
Parameters: {"id"=>"134"}
Aj Load (0.4ms) SELECT "ajs".* FROM "ajs" WHERE "ajs"."id" = ? LIMIT 1 [["id", 134]]
Completed 400 Bad Request in 4ms
ActionController::ParameterMissing (param is missing or the value is empty: aj):
app/controllers/ajs_controller.rb:98:in `aj_params'
app/controllers/ajs_controller.rb:69:in `block in update'
app/controllers/ajs_controller.rb:68:in `update'
Rendered /home/liplw015/.rvm/gems/ruby-2.1.2/gems/actionpack- 4.1.2/lib/action_dispatch/middleware/templates/rescues/_source.erb (0.9ms)
Rendered /home/liplw015/.rvm/gems/ruby-2.1.2/gems/actionpack-4.1.2/lib/action_dispatch/middleware/templates/rescues/_trace.text.erb (1.3ms)
Rendered /home/liplw015/.rvm/gems/ruby-2.1.2/gems/actionpack-4.1.2/lib/action_dispatch/middleware/templates/rescues/_request_and_response.text.erb (0.9ms)
Rendered /home/liplw015/.rvm/gems/ruby-2.1.2/gems/actionpack-4.1.2/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb (22.5ms)
Started PATCH "/ajs" for 127.0.0.1 at 2014-07-14 09:38:10 +0530
ActionController::RoutingError (No route matches [PATCH] "/ajs"):
actionpack (4.1.2) lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call'
your route is wrong, include id in route
match '/ajs/:id' => 'ajs#update', :via => :patch

How do you get rspec to output what it encountered rather than it "didn't find what it expected"?

I have been struggling to using ruby/rspec/capybara/devise to test my code. A simple test I am trying to write is for signing in. I have a valid user sign in and expect to see an h1 tag as defined in the following code:
describe "Authentication" do
subject { page }
describe "with valid information" do
let(:user) { FactoryGirl.create(:user) }
before { sign_in_with user.email }
it { should have_css('h1', text: "Welcome to the Test") }
end
end
Problem is that I get this in return:
1) Authentication signin page with valid information
Failure/Error: it { should have_css('h1', text: "Welcome to the Test") }
expected css "h1" with text "Welcome to the Test" to return something
# ./spec/requests/authentication_pages_spec.rb:34:in `block (4 levels) in <top (required)>'
Is there a way to output what the test found in the h1 (or that it didn't find it at all?) instead of it didn't find what it expected? There is a good chance my sign_in method is not working, but I can't validate that because I'm not sure what the test sees after sign_in_with executes.
Thanks and happy to provide more context if it's helpful.
EDIT
Updated code to reflect subject of tests.
... I'm not sure what the test sees after sign_in_with executes.
You can open a snapshot of the current page with save_and_open_page:
describe "with valid information" do
let(:user) { FactoryGirl.create(:user) }
before { sign_in_with user.email }
it { save_and_open_page; should have_css('h1', text: "Welcome to the Test") }
end
There is no subject, you can't use it to represent result. For Capybrara, you need to check the page object returned.
Let's rewrite the test like this:
describe "with valid information" do
let(:user) { FactoryGirl.create(:user) }
before do
sign_in_with user.email
end
it "signs in successfully" do
expect(page).to have_css('h1', text: "Welcome to the Test")
end
end
Or better, with Capybara story DSL
feature "User sign in" do
given(:user) { FactoryGirl.create(:user) }
scenario "with valid information " do
sign_in_with user.email
expect(page).to have_css('h1', text: "Welcome to the Test")
end
scenario "with invalid filing" do
sign_in_with "foo#bar.com"
expect(page).to have_text("Invalid email or password")
end
end

Rspec method missing for stub_chain with Rails Model

I am attempting to use stub_chain to mock a series of calls in a controller action. However it is complaining about a method not found error. After a bunch of searching, I didn't really find any info relating to this specific error, so I figure I am missing something fairly obvious. Any ideas?
Thanks.
Here is the error:
Admin::AccountsController GET #index with accounts
Failure/Error: before(:each) { Account.stub_chain(:scoped, :page, :order).returns([account]) }
NoMethodError:
undefined method `stub_chain' for #<Class:0x007f96c6448158>
# ./spec/controllers/admin/accounts_controller_spec.rb:11:in `block (4 levels) in <top (required)>'
Source for the spec:
#spec/controllers/admin/accounts_controller.rb
describe 'GET #index' do
context 'with accounts' do
let(:account) { FactoryGirl.build_stubbed(:account) }
before(:each) { Account.stub_chain(:scoped, :page, :order).returns([account]) }
subject { get :index }
it { should render_template(:index) }
it { should assign_to(:accounts) }
it { should respond_with(:success) }
it { should_not set_the_flash }
end
end

named path not being recognized in rspec

I am using Rails 3.1.0 and Rspec 2.12.2. I want to have an action that we post to via jQuery to:
/path/api/save-reply
I have the following spec:
describe 'test adding new mb post' do
it 'shall add a new mb post' do
post :save_reply, mb_detail: 'here is my detail', timestamp_id: 123, parent_id: 50, depth: 0
end
end
with the following named route:
routes.rb
post '/api/save-reply' => 'api_mb#save_mb_reply', :as => :save_reply, :defaults => { :format => 'json' }
And get the following error:
1) ApiMbController test adding new mb post shall add a new mb post
Failure/Error: post :save_reply, mb_detail: 'here is my detail', timestamp_id: 123, parent_id: 50, depth: 0
AbstractController::ActionNotFound:
The action 'save_reply' could not be found for ApiMbController
# ./spec/controllers/api_mb_controller_spec.rb:16:in `block (3 levels) in <top (required)>'
Shouldn't the spec be calling the correct path 'save_mb_reply' rather than trying 'save_reply'? What am I doing wrong?
If I run:
Mon Jan 07$ bundle exec rake routes | grep save_reply
save_reply POST /arc/v1/api/save-reply(.:format) {:format=>"json", :controller=>"api_mb", :action=>"save_mb_reply"}
Mon Jan 07$
thx in advance
Controller specs don't use routing for determing what to call - they just call the method you specify.