0

我正在测试注册用户可以创建帖子的帖子控制器。

  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

结尾

感谢帮助

我的 factory.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
4

1 回答 1

1

这是一个控制器规格,而不是模型规格,所以不要测试你的模型。

Post.any_instance.stub(:generate_slug)

我还强烈建议您只对每个规格进行一次测试。您目前正在执行三个特定测试,并且还间接测试 sign_in。我删除了所有控制器规范的登录方面,并通过我的请求规范测试登录。

我希望这会有所帮助。

于 2013-01-31T19:11:40.143 回答