我正在尝试解决我的 rspec 测试以创建对象的问题,但无论我尝试什么,计数似乎都没有改变。我确定我在这里遗漏了一些非常基本的东西。
这是我的rspec:
before do
login_account_admin(user)
@group = Factory(:group, :code => "GR_111", :description => "description for GR_111")
Group.stub!(:find).and_return(@group)
end
describe "#create" do
it "should create a new group object" do
group_params = {:code => "NEW_GROUP", :description => "description for NEW_GROUP"}
expect {
post :create, :service_id => service, :cdb_group => group_params, :button => "save", :format => "js"
}.to change(Group, :count).by(1)
end
it "should not create a new group object with invalid code format" do
group_params = {:code => "invalid", :description => "description for invalid code name group"}
expect {
post :create, :service_id => service, :cdb_group => group_params, :button => "save", :format => "js"
}.to_not change(Group, :count)
end
end
“code”参数只能包含大写字母A到Z、0-9和_
这是#create的控制器方法定义
def create
@group = Group.new(params[:cdb_group])
respond_to do |format|
if params[:button] == "cancel"
format.js { render "hide_new"}
elsif @group.save
format.js {
render 'show_new_group'
}
format.html { redirect_to(some_path(@service), :notice => 'Group was successfully created.') }
format.xml { head :ok }
end
end
end
这是组模型:
class Group < ActiveRecord::Base
validates_uniqueness_of :code
validates_presence_of :code, :description
validates_format_of :code, :without => /[^A-Z0-9_]/ , :message => 'can only contain uppercase letters A to Z, 0-9 and _'
end
每当我尝试运行 rspec 测试时,我都会收到以下错误:-
1) GroupsController User As Account Admin goes to #create should create a new group object
Failure/Error: expect {
count should have been changed by 1, but was changed by 0
# ./spec/controllers/groups_controller_spec.rb:51
2) GroupsController User As Account Admin goes to #create should not create a new group object with invalid code format
Failure/Error: expect {
count should not have changed, but did change from 2 to 1
# ./spec/controllers/groups_controller_spec.rb:58
在这方面的任何帮助将不胜感激?