我正在测试注册用户可以创建帖子的帖子控制器。
it 'should allow registered user to create post' do
user = FactoryGirl.create(:user)
sign_in user
expect {
article_params = FactoryGirl.attributes_for(:post)
post :create, :article => article_params
}.to_not change(Post, :count)
response.should redirect_to(new_user_session_path)
flash[:alert].should == "You need to sign in or sign up before continuing."
end
我收到错误
Failure/Error: post :create, :article => article_params
NoMethodError:
undefined method `mb_chars' for nil:NilClass
这是因为我的模型中有generate_slug。 Post.rb
include Translit
#slug
before_validation :generate_slug
def generate_slug
self.slug = translit(title)
end
在Translit.rb中我有mb_chars
# encoding: utf-8
module Translit
def translit (string)
table = {
"ё"=>"yo","№"=>"#",
"а"=>"a","б"=>"b","в"=>"v","г"=>"g",
"д"=>"d","е"=>"e","ж"=>"zh","з"=>"z",
"и"=>"i","й"=>"y","к"=>"k","л"=>"l",
"м"=>"m","н"=>"n","о"=>"o","п"=>"p","р"=>"r",
"с"=>"s","т"=>"t","у"=>"u","ф"=>"f","х"=>"h",
"ц"=>"ts","ч"=>"ch","ш"=>"sh","щ"=>"sch","ъ"=>"'",
"ы"=>"yi","ь"=>"","э"=>"e","ю"=>"yu","я"=>"ya"
}
string = string.mb_chars.downcase
table.each do |translation|
string.gsub!(/#{translation[0]}/, translation[1])
end
string.parameterize
end
端
感谢您的帮助
我的个工厂.rb是
FactoryGirl.define do
factory :user do
email "testspec@gmail.com"
password "password"
password_confirmation "password"
end
factory :post do
title "Deploying through ssh"
body "This is post about ssh"
end
end
答案 0 :(得分:1)
这是控制器规格,而不是型号规格,因此请勿测试您的型号。
Post.any_instance.stub(:generate_slug)
我还强烈建议您每个规格只进行一次测试。您目前正在进行三项特定测试,并且还间接测试sign_in。我将所有控制器规范的登录方面存根,并且测试登录通过我的请求规范工作。
我希望有所帮助。