那天看到IE有战友贴了这个书,就想找个时间读读,有收获随笔记下来收获
据说这种格式validate可以多个写一起,不用重复
validates :description, :presence => true, :length => { :minimum => 10 }
这个nested很多地方有了,codeschool railscast和guide
project_ticket_path(@project, @ticket)
这个是关联的,就是相当于project_id:integer
rails generate model ticket title:string description:text project:references
初始化一个关联实例
def new
@ticket = @project.tickets.build
end
<% @project.tickets.each do |ticket| %>
<li>
#<%= ticket.id %> - <%= link_to ticket.title, [@project, ticket] %>
没记着steps
Given /^I am signed in as them$/ do
steps(%Q{
Given I am on the homepage
When I follow "Sign in"
And I fill in "Email" with "#{@user.email}"
And I fill in "Password" with "password"
And I press "Sign in"
Then I should see "Signed in successfully."
})
end
let和before的差别是,before是所有context都加载,let只有context里用到user才加载
describe ProjectsController do
let(:user) do
user = Factory(:user)
user.confirm!
user
end
context "standard users" do
it "cannot access the new action" do
sign_in(:user, user)
end
end
context "standard users" do
it "cannot access the new action" do
sign_in(:user, user)
get :new
response.should redirect_to(root_path)
flash[:alert].should eql("You must be an admin to do that.")
end
end
{ "new" => "get",
"create" => "post",
"edit" => "get",
"update" => "put",
"destroy" => "delete" }.each do |action, method|
it "cannot access the #{action} action" do
sign_in(:user, user)
send(method, action.dup, :id => project.id)
response.should redirect_to(root_path)
flash[:alert].should eql("You must be an admin to do that.")
end
end
...
end
其中用到的Factory Girl定义如下
#factories/user_factory.rb:
Factory.define :user do |user|
user.sequence(:email) { |n| "user#{n}@ticketee.com" }
user.password "password"
user.password_confirmation "password"
end
#其中sequence用于产生不重复的数字,以便生成email不重复
rspec要加载上Fatorygirl定义的User,还要处理一个lib调用include上
#spec/support/factories.rb
#spec/controllers/projects_controller_spec.rb
Dir[Rails.root + "factories/*.rb"].each do |file|
require file
end
Rspec用到了sign_in所以要加载devise到rspec
RSpec.configure do |config|
config.mock_with :rspec
config.include Devise::TestHelpers
end
说到rspec看这个更舒服
http://pure-rspec-scotruby.heroku.com/
cucumber里检查页面是否存在元素context_contain capybara的语法
#features/step_definitions/link_steps.rb
Then /^I should see the "([^\"]*)" link$/ do |text|
page.should(have_css("a", :text => text),
"Expected to see the #{text.inspect} link, but did not.")
end
Then /^I should not see the "([^\"]*)" link$/ do |text|
page.should_not(have_css("a", :text => text),
"Expected to not see the #{text.inspect} link, but did.")
end
检查是否admin
- admins_only do
= link_to "New Project", new_project_path
def admins_only(&block)
block.call if current_user.try(:admin?)
nil
end